How to use Curl in PHP to retrieve data from other page

In some case if you want to retrieve data from another user i am normally using file_get_contents($link);

But some sites disabled file access by using file_get_content(), in that situation we can use Curl functions of PHP. For this you must need to enable CURL in your PHP server. API_URL contains a URL of API that you want to access. If you need to pass Username and password for API then set CURLOPT_USERPWD. In below code snippet API_ID is a username and API_SECRET is password that required for API, If it does not required then you can omit it.

$url = API_URL;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD,  API_ID . ':' . API_SECRET);  //optional
$result = curl_exec($ch);

if ($result === FALSE)
	throw new Exception(curl_error($ch), curl_errno($ch));
$result = json_decode($result);
// Perform operation with $result return from $url

If you receive PHP cURL error code 60 then you need to download certificates from https://curl.haxx.se/ca/cacert.pem.

And after downloading paste it in C:\wamp\bin\apache\apache2.4.9\bin\ and update php.ini file

curl.cainfo = "C:/wamp/bin/php/php5.5.12/cacert.pem"

One thought on “How to use Curl in PHP to retrieve data from other page

Leave a Reply

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