Coder Perfect

How can I make file get contents() operate over HTTPS?

Problem

I needed to apply a workaround for CURL while setting up credit card processing. The following code worked OK on the test server (which wasn’t calling an SSL URL), but it now fails with the error message “failed to open stream” when tested on the working server using HTTPS.

function send($packet, $url) {
  $ctx = stream_context_create(
    array(
      'http'=>array(
        'header'=>"Content-type: application/x-www-form-urlencoded",
        'method'=>'POST',
        'content'=>$packet
      )
    )
  );
  return file_get_contents($url, 0, $ctx);
}

Asked by James Simpson

Solution #1

To enable the https wrapper, type:

If this line does not exist in your php.ini file, you need add it:

extension=php_openssl.dll

allow_url_fopen = On

Answered by hassan

Solution #2

To see if a https wrapper for your php scripts is available, run the following script.

$w = stream_get_wrappers();
echo 'openssl: ',  extension_loaded  ('openssl') ? 'yes':'no', "\n";
echo 'http wrapper: ', in_array('http', $w) ? 'yes':'no', "\n";
echo 'https wrapper: ', in_array('https', $w) ? 'yes':'no', "\n";
echo 'wrappers: ', var_export($w);

The final product should look like this:

openssl: yes
http wrapper: yes
https wrapper: yes
wrappers: array(11) {
  [...]
}

Answered by VolkerK

Solution #3

$url= 'https://example.com';

$arrContextOptions=array(
      "ssl"=>array(
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ),
    );  

$response = file_get_contents($url, false, stream_context_create($arrContextOptions));

This will allow you to retrieve material from a URL, regardless of whether it is HTTPS or not.

Answered by Dushyant Dagar

Solution #4

Try the following.

function getSslPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

Answered by Benjamin Crouzier

Solution #5

This is most likely due to the fact that your target server does not have a valid SSL certificate.

Answered by Emil Vikström

Post is based on https://stackoverflow.com/questions/1975461/how-to-get-file-get-contents-to-work-with-https