Intro to CURL with PHP

CURL is a command-line style function to send data via a URL. WikiPedia has a more detailed article on what it is and does.

Preface – your php installation on your server must be CURL-enabled. You can download the CURL package for free. This article assumes your server is ready to go.

While CURL is not an alternative to AJAX, it can be used in similar situations where you need to send data out somewhere without the user having to go there. In it’s most basic operation, you have some data to send out to a script.

We need a a simple function to handle our data, a page to process said data, and a source page where the function is called from.

The call page is simple. Something as simple as:

where $var1 -3 are predefined, or even hard-coded strings will suffice for basic testing. This php block sets us up to print the output of our function:

function sendCURL($var1, $var2, $var3, $referrer="") {
$mycurl = curl_init(""); $fields = array(
"var1" => $var1,
"var2" => $var2,
"var3" => $var3
); $curlagent = array(
"User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"
); curl_setopt($mycurl, CURLOPT_POST, 1);
curl_setopt($mycurl, CURLOPT_HEADER, 0);
curl_setopt($mycurl, CURLOPT_NOBODY, 0);
curl_setopt($mycurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($mycurl, CURLOPT_REFERER, $referer);
curl_setopt($mycurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($mycurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($mycurl, CURLOPT_HTTPHEADER, $curlagent);
curl_setopt($mycurl, CURLOPT_POSTFIELDS, $fields);

$response = curl_exec($mycurl);
curl_close ($mycurl); return $response;

This function is your basic CURL request. Setting the variables into an array to pass, and setting headers and Options within CURL on how to process it. The only real change you will need to make to this function are your variables in the array and your URL that you wish to send it to.

The curl_processor_page.php is no different than any other php page that can handle incoming $_REQUEST parameters. Those var’s need to be set up in the function that the page is looking for, perhaps a username, password, and a realname.

What that script does is entirely up to you. I won’t post an example, because I don’t want anyone to think that you can only do one method with this function set.

You could have the response be ANYTHING that gets returned from the processor page. A remote login, a simple welcome screen, or even creating accounts (how do you think those auto MySpace friend adder bots work?!)

A useful tool when playing with CURL is the LiveHTTP Headers plugin for FireFox. This plugin let’s you see what’s getting sent via HTTP AS it happens. It’s a real-time watchdog and is very useful for debugging CURL requests to see where it’s bombing.

Happy CURLing 🙂

Leave a comment

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