user3079266
user3079266

Reputation:

Connect to https server with PHP

I need to get data from a webpage on a server which uses the https protocol (i.e. https://site.com/page). Here's the PHP code I've been using:

$POSTData = array('');
$context = stream_context_create(array(
    'http' => array(
    //'ignore_errors' => true,
    'user_agent' => "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36",
    'header' => "User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/522.11.1 (KHTML, like Gecko) Version/3.0.3 Safari/522.12.1",
    'request_fulluri' => true,
    'method'  => 'POST',
    'content' => http_build_query($POSTData),
    )
));
$pageHTML = file_get_contents("https://site.com/page", FALSE, $context);
echo $pageHTML;

However, this doesn't seem to work, giving out a Warning: file_get_contents with no information on the error. What might be the case, and how do I work around it to connect to the server and get the page?

EDIT: Thanks to everyone who answered, my problem was that I was using an HTTP proxy, which I removed from the code so that it wouldn't confuse you, as I thought it couldn't possibly have been the problem. To make the code load an HTTPS page via an HTTP proxy, I modified the stream_context_create I used like this:

    stream_context_create(array(
    'https' => array(
    //...etc

Upvotes: 1

Views: 1622

Answers (1)

Wes H
Wes H

Reputation: 587

Have a look at cURL if you haven't already. With cURL you can remotely access a webpage/API/file and have it downloaded to your server. The curl_setopt() function allows you to specify whether or not to verify the certificate of the remote server

$file = fopen("some/file/directory/file.ext", w);
$ch   = curl_init("https://site.com/page");
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //false to disable the cert check if needed

$data = curl_exec($ch);
curl_close($ch);
fclose($file);

Something like that will allow you to connect to an HTTPS server and then download the file that you want. If you know the server has a valid certificate (i.e. you aren't developing on a server that doesn't have a valid certificate) then you can leave out the curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); line, as cURL will attempt to verify the certificate by default.

cURL also has the curl_getinfo() function that will give you details about the most recently processed transfer that will help you debug the program.

Upvotes: 1

Related Questions