by Marc Plotz
You probably know that cURL is a wonderful tool for extracting data from a Web page — that’s a given if you are a developer worth your salt. However, in this article, I want to show you how to use cURL to do things for you. We will start by exploring cURL in detail and then move on to use a very cool script to update our Facebook status.
Of course, you need a more than basic understanding of PHP for this article.
What Is cURL?
In 1997, a developer named Daniel Stenberg started writing cURL as a command-line interface way to transfer files using FTP, HTTP, Gopher and many more. Since then, many people have provided further contributions toward the technology. Today, cURL is a big part of PHP and a very powerful tool to have in your developer toolbox.
To check if you have cURL installed on your computer, fire up your command line and type:
$ cURL -V
On my MacBook, I get this result:
curl 7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3 Protocols: tftp ftp telnet dict ldap http file https ftps Features: GSS-Negotiate IPv6 Largefile NTLM SSL libz
If you don’t get an error on the point above, then you are generally OK. Now, to test cURL, try something like this:
$ cURL www.google.com
And the result I get is:
$ curl www.google.com <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>302 Moved</TITLE></HEAD><BODY> <H1>302 Moved</H1> The document has moved <A HREF="http://www.google.co.za/">here</A>. </BODY></HTML>
Not quite the result I was looking for, but simple enough to know that CURL actually works. I got that page because Google wants to redirect me to my local version of Google, not www.google.com but www.google.co.za in my case.
Now, the good news is that PHP has some very powerful built-in functions that take away the need for command line interfacing. Let’s take a look at this now.
Using cURL and PHP for Scripting
In order to use cURL to get the contents of a site within a PHP script, we can use the following code:
<?php $ch = curl_init("http://www.example.com/"); $fp = fopen("example.txt", "w"); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp);
The above code will grab the content from www.example.com and chuck it into the file example.txt.
Breaking it down, we see that:
$ch = cURL_init("http://www.example.com/"); // Init and tell CURL where we will be visiting. $fp = fopen("example.txt", "w"); // Open a file for writing. cURL_setopt($ch, CURLOPT_FILE, $fp); // Tell CURL we're writing to $fp cURL_setopt($ch, CURLOPT_HEADER, 0); // Do not include a header in the output cURL_exec($ch); // Execute! cURL_close($ch); // Close - shut down CURL, we're done. fclose($fp); // Close the file for reading.
Do yourself a favor and test this script — it works well and shows the beginning of some very powerful scripting power we have at our disposal.