PHP cURL: how to connect via HTTPS?

I need to make a simple GET request for the EC2 request APIs with a regular URL query string. HTTPS protocol. How to send a request using PHP cURL.

+6
php
source share
4 answers

Example:

$url = "https://example.com"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); $result = curl_exec($ch); curl_close($ch); print_r($result); 

CURLOPT_SSL_VERIFYPEER

Check if the ad hoc certificate is valid or invalid / expired.

CURLOPT_SSL_VERIFYHOST quote from php manual :

1 to verify the existence of a common name in the SSL certificate. 2 to check for a common name and also make sure that it matches the host name.

+12
source

Sending a request via curl to an HTTPS URL is not that difficult in terms of PHP code.

Something like this should work fine (I just tried this piece of code on my machine, Windows, PHP 5.3):

 $url = 'https://.../...'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($ch); curl_close($ch); echo $data; 

And it outputs the result perfectly: the same thing that I get in my browser when I try to access the https:// URL; with the exception of CSS, of course.


You can take a look at the curl_setopt : there are many options, and some of them may be useful in your particular case curl_setopt

Here I used CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST ; I’m not sure that you will need those who have Amazon, but I had to use them, otherwise this part of the code did not work, but this may be due to the fact that the certificate that I use is by itself ... Try with with them and without them, and you will quickly find out if you need them.

+4
source

If you want to configure CURL to blindly accept a certificate, you can set the CURLOPT_SSL_VERIFYPEER parameter to false.

 $url = 'https://www.example.com/abc'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Blindly accept the certificate curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($ch); curl_close($ch); var_dump($response); 
+2
source

You can also use the Zend Framework and the cURL adapter to help with this task. More here

+1
source

All Articles