How to use the PHP cURL module to make HTTP requests from PHP

Some of my previous posts talked about making HTTP/web requests from PHP with a focus on the PECL_HTTP request module:

The last post mentioned above covered using the built-in file_get_contents() as an alternative if you are unable to install the HTTP PECL extension or need minimal HTTP functionality. This post will look at a third method of making HTTP requests from PHP, using the PHP Client URL Library AKA cURL library. The PHP cURL library essentially uses the cURL library from the cURL command line utility and makes the calls available via PHP functions.

Installing the PHP cURL library on Ubuntu requires just a couple simple steps:

  • PHP needs to compile in the cURL library but if you are using Ubuntu you can simply execute the following shell command instead of doing a custom PHP build:
    sudo apt-get install php5-curl
  • Restart Apache once the library has installed.
  • Call a page with the phpinfo() function and look for a “curl” section. It should be listed there if everything installed correctly:

    curlinfo1

Once the cURL library is added you can call the curl functions which are documented here. The following simple example makes a call to www.example.com. You will notice that I did not “echo” the return of curl_exec() to display it. This is because by default, the curl_exec() function displays the result and returns a true on success, false on failure.

<?php
 
$curl_handle = curl_init("http://www.example.com/");
curl_exec($curl_handle);
curl_close($curl_handle);
 
?>

If you want to assign the output to a variable so you can do something with it, you will need to set the CURLOPT_RETURNTRANSFER option:

<?php
 
$curl_handle = curl_init("http://www.example.com/");
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
$results = curl_exec($curl_handle);
curl_close($curl_handle);
echo $results;
 
?>

The PHP cURL library has a variety of options you can set using the curl_setopt() function. This includes setting GET and POST requests, setting fields for each, etc.

That is the five minute version of the PHP cURL library. Another quick way to make an HTTP request is to just make a system call to the “wget” command utility which is included on most *nix systems:

<?php
 
echo system("wget -O - http://www.example.com");
 
?>

This pretty cool but I think I prefer the other methods because they all run under the Apache process. That’s it for this post!

Leave a Reply