PHP cURL Tutorial and Example

Do you want to learn how to use cURL in PHP? Well, if so then this tutorial is for you. But before anything else, what is cURL?

cURL is a command line tool for transferring files with URL syntax. The strong point of cURL is the number of data transfer protocols it supports. It is distributed under the MIT License which makes cURL free software. It supports FTP, FTPS, HTTP, HTTPS, TFTP, SCP, SFTP, Telnet, DICT, FILE and LDAP. – based on Wikipedia’s definition

PHP cURL allows you to read websites, make automated logins, upload files and many more. I’m personally using it to automate updating of my many websites.

Now that you know what cURL is, I think it’s time to look at some code.

$ch = curl_init ("http://www.yahoo.com");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$yahoo = curl_exec ($ch);

The simple example above simply gets the contents of http://www.yahoo.com and saves it in the variable $yahoo. Here’s a line-by-line explanation:

$ch = curl_init (“http://www.yahoo.com”);

Initialize curl with the URL of yahoo

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

Tell php curl that we want the data returned to us instead of being displayed

$yahoo = curl_exec ($ch);

Execute curl and put the output in $yahoo.

But, that’s too simple! That can be done in simpler ways with PHP’s file functions such as file() and file_get_contents()! True but that’s where the comparison ends.

The power of PHP cURL lies within the curl_setopt() function. This function instructs cURL of what exactly we want to do. Let’s say, what if a webpage that you want to access checks for the HTTP_REFERER header? Or perhaps, what if you need to access a webpage that works correctly only if cookies are enabled?

Here’s another example… This time we specify the HTTP_REFERER…

$ch = curl_init ("http://www.somedomain.com/page2.php");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_REFERER, "http://www.somedomain.com/page1.php");
$page = curl_exec ($ch);

In this example, the CURLOPT_REFERER line tells cURL to set the HTTP_REFERER header to http://www.somedomain.com/page1.php.

PHP cURL can do more. It can send POST data, it can log on to a website and automate tasks as if it was a real person and much more. That’s it for now and I hope this PHP cURL Tutorial helped you.

Leave a comment