Transfer data to https (Secure) url using PHP CURL

What is curl and php-curl?

Curl is library and command line tool, which allow transferring data to url using various protocol like http, https, ftp etc.
With the help of curl, We can send http requests to server using various methods like GET, POST etc.
Php curl is php extension, which helps to send these requests to server using PHP functions. E.g. If you want to post some data to url from pho page, we can do this by using php curl. Like below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// create a new cURL resource
$url="http://www.example.com";
 
//Intialize curl and provide url
$ch = curl_init($url);
 
// set URL and other appropriate options
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
// grab URL and pass it to the browser
 
$response=curl_exec($ch);
//check if we get response or not
if(!$response){
$errors=curl_error($ch);
echo "Error fetching url " .$errors;
}
echo $response;
// close cURL resource, and free up system resources
curl_close($ch);

Send request to HTTPS url using curl

Above code will not be able to send the request to secure(https) url as url is not plain http url and it will get failed and return error.

To allow curl to send requests to https url, we need to apply few more parameters using curl_setopt method. These are:

1
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

After adding these above parameters to curl, our code will like below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// create a new cURL resource
$url="https://www.example.com";
 
//Intialize curl and provide url
$ch = curl_init($url);
 
// set URL and other appropriate options
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
 
// grab URL and pass it to the browser
 
$response=curl_exec($ch);
//check if we get response or not
if(!$response){
$errors=curl_error($ch);
echo "Error fetching url " .$errors;
}
echo $response;
// close cURL resource, and free up system resources
curl_close($ch);

In this way we can easily sends request to https url. To see complete list of parameters allowed in curl_setopt or cur_setoptarray please visit following url
http://php.net/manual/en/function.curl-setopt.php

Leave a Reply

Your email address will not be published. Required fields are marked *

*


Skip to toolbar