Friday, May 4, 2012

file_get_contents with https?


I'm working on setting up credit card processing and needed to use a workaround for CURL, and the following code worked fine when I was using the test server (which wasn't calling an SSL URL), but now when I am testing it on the working server with https, it doesn't work ("failed to open stream").




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);
}


Source: Tips4all

6 comments:

  1. Try the following script to see if there is an https wrapper available for your php scripts.

    $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_dump($w);


    the output should be something like

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

    ReplyDelete
  2. This is probably due to your target server not having a valid SSL certificate.

    ReplyDelete
  3. Taken from the comments in the PHP manual for stream_context_create

    edit: removed code as it was not helpful

    HTTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.
    Also, make sure the target server has a valid certificate, the firewall allows outbound connections and allow_url_fopen in php.ini is set to true.

    ReplyDelete
  4. To alow https wraper :
    - the php_openssl extension must existe and anabled
    - allow_url_include must be set to on

    in the php.ini file you add this lines if not exists:

    extension=php_openssl.dll

    allow_url_include = On


    Ragards

    ReplyDelete
  5. I had the same error. Setting allow_url_include = On in php.ini fixed it for me.

    ReplyDelete
  6. Sometimes a server will choose not to respond based on what it sees or doesn't see in the http request headers (such as an appropriate user agent). If you can connect with a browser, grab the headers it sends and mimic them in your stream context.

    ReplyDelete