PHP

PHP Curl Get/Post Example

If you have worked with Linux, you will have probably used cURL for downloading resources from the Internet. This powerful library can also be used in PHP scripts, and that is what we are going to see in this example.

For this example, we will use:

  • Ubuntu (14.04) as Operating System.
  • Apache HTTP server (2.4.7).
  • PHP (5.5.9).

 
 

Tip
You may skip environment preparation and jump directly to the beginning of the example below.

1. Preparing the environment

1.1. Installation

Below, commands to install Apache, PHP and PHP cURL library are shown:

sudo apt-get update
sudo apt-get install apache2 php5 libapache2-mod-php5 php5-curl
sudo service apache2 restart

1.2. PHP configuration

In /etc/php/apache2/php.ini file, we need to include the cURL extension, in order to use it:

extension=php_curl.so

Don’t forget to restart Apache after doing any change.

2. GET requests

Let’s see how we can use cURL to create GET requests:

curl_get.php

<?php

/**
 * Checks if the given parameters are set. If one of the specified parameters
 * is not set, die() is called.
 *
 * @param $parameters The parameters to check.
 */
function checkGETParametersOrDie($parameters) {
    foreach ($parameters as $parameter) {
        isset($_GET[$parameter]) || die("Please, provide '$parameter' parameter.");
    }
}

/**
 * Gets the GET parameters.
 *
 * @return GET parameter string.
 */
function stringifyParameters() {
    $parameters = '?';

    foreach ($_GET as $key => $value) {
        $key = urlencode($key);
        $value = urlencode($value);
        $parameters .= "$key=$value&";
    }

    rtrim($parameters, '&');

    return $parameters;
}

/**
 * Creates the cURL request for the given URL.
 *
 * @param $url The URL to create the request to.
 * @return The cURL request to the url; false if an error occurs.
 */
function createCurlRequest($url) {
    $curl = curl_init();

    if (!$curl) {
        return false;
    }

    $configured = curl_setopt_array($curl, [
        CURLOPT_URL => $url . stringifyParameters(),
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_RETURNTRANSFER => true
    ]);

    if (!$configured) {
        return false;
    }

    return $curl;
}

// Flow starts here.

checkGETParametersOrDie(['url']);

$url = $_GET['url'];

$curl = createCurlRequest($url);

if (!$curl) {
    die('An error occured: ' . curl_error($curl));
}

$result = curl_exec($curl);

if (!$result) {
    die('An error occured: ' . curl_error($curl));
}

echo '<div>The result of the cURL request:</div>';
echo '<hr>';
echo $result;

curl_close($curl); // Don't forget to close!

This is what we have done:

  • First, we created a cURL session, with curl_init() function, as in line 41. If some error occurs, false will be returned, so we have to check it before continuing (line 43).
  • Once we have created successfully the cURL session, we have to configure it, as we do with curl_setopt_array() function. In this case, we have configured it with the following options:
    • The URL itself. For GET requests, we just have to specify the URL with the parameter string, in key=value format, as you already know. Note how is the parameter string constructed in stringifyParameters() function: the values should be encoded to URL encoding, with urlencode() function (lines 24 and 25).
    • The CURLOPT_FOLLOWLOCATION option to true. This is for following the 3XX HTTP redirections. If we set to false, and the specified URL makes a redirection, we won’t reach the final URL.
    • The CURLOPT_RETURNTRANSFER option to true. This allows to save the HTTP response into a variable. If set to false, the response will be printed directly.
  • We should always check that the cURL functions don’t return any errors, checking the return values of the functions. When false is returned, we can get the information of the last error for the given cURL session with curl_error() function, as in lines 69 and 75.
  • If any error has occurred initializing and configuring the cURL session, we can proceed to execute it, just calling curl_exec() function, specifying for which session we are executing the request. In this case, as we configured the CURLOPT_RETURNTRANSFER option, we can save the response value into a variable.
  • Finally, when we have ended the cURL session handling, we must close it, curl_close() function.

We can test this script, entering, for example, localhost/path/to/curl_get.php?url=webcodegeeks.com&s=php in the browser. We will see that the output generated by the script, is the same of that which we would have received making a search in the above search box, in this page, entering php.

3. POST requests

For POST requests, we have to configure the cURL options in a slightly different way:

curl_post.php

// ...

function createCurlRequest($url) {
    $curl = curl_init();

    if (!$curl) {
        return false;
    }

    $configured = curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => stringifyParameters(),
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_RETURNTRANSFER => true
    ]);

    if (!$configured) {
        return false;
    }

    return $curl;
}

// ...

Note that, when setting the URL, we just set the URL itself without the parameters, that’s for GET requests. Those parameters are specified in CURLOPT_POSTFIELDS option. And, apart from that, we are specifying that the request will be made for POST method, with CURLOPT_POST option.

The only difference between cURL POST and GET requests is the configuration of the session. The rest of the script, can be the same for both.

4. Encapsulating operations in a cURL class

When we are going to use cURL in a project, is recommendable to have encapsulated all the code instead of using every time the functions we have used above, because we would be repeating much code, and the possibilities of introducing errors would increase. So, we are going to create a class that encapsulates this logic.

curl_class.php

<?php

/**
 * Methods for cURL request handling.
 */
class CURL {

    /**
     * The cURL request object.
     */
    private $request;

    /**
     * CURL class constructor.
     *
     * @throws Exception if an error occurs initializating.
     */
    public function __construct() {
        $this->request = curl_init();

        $this->throwExceptionIfError($this->request);
    }

    /**
     * Configure the cURL request.
     *
     * @param $url The target url.
     * @param $urlParameters The array of parameters, with 'key' => 'value' format.
     * @param $method 'GET' or 'POST'; 'GET' by default.
     * @param $moreOptions Any other options to add to the cURL request. By default,
     *    'CURLOPT_FOLLOWLOCATION' (follow 3XX redirects) and 'CURLOPT_RETURNTRANSFER'
     *    (return HTTP response as a value, instead of outputting directly) are set.
     * @throws Exception if an error occurs configurating.
     */
    public function configure($url, $urlParameters = [], $method = 'GET',
        $moreOptions = [CURLOPT_FOLLOWLOCATION => true, CURLOPT_RETURNTRANSFER => true]) {

        curl_reset($this->request);

        switch ($method) {
            case 'GET':
                $options = [CURLOPT_URL => $url . $this->stringifyParameters($urlParameters)];
                break;

            case 'POST':
                $options = [
                    CURLOPT_URL => $url,
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => $this->stringifyParameters($urlParameters) 
                ];

                break;

            default:
                throw new Exception('Method must be "GET" or "POST".');
                break;
        }

        $options = $options + $moreOptions; 

        foreach ($options as $option => $value) {
            $configured = curl_setopt($this->request, $option, $value);

            $this->throwExceptionIfError($configured);
        }
    }

    /**
     * Executes the cURL request for the options configured.
     *
     * @return The return value of curl_exec(). If CURLOPT_RETURNTRANSFER was configured,
     *     the return value will be the HTTP response. In other case, a true value (or false
     *     if some error has occured).
     * @throws Exception if an error occurs executing.
     */
    public function execute() {
        $result = curl_exec($this->request);

        $this->throwExceptionIfError($result);

        return $result;
    }

    /**
     * Closes cURL session.
     */
    public function close() {
        curl_close($this->request);
    }

    /**
     * Checks if a curl_* function returns success or failuer, throwing an exception
     * with the cURL error message if it has failed.
     *
     * @param $success IF the curl function has succeeded or not.
     * @throws Exception if the curl function has failed.
     */
    protected function throwExceptionIfError($success) {
        if (!$success) {
            throw new Exception(curl_error($this->request));
        }
    }

    /**
     * Creates a string of GET parameters.
     *
     * @param $parameters Parameter array.
     * @return Parameters in string format: '?key1=value1&key2=value2'
     */
    protected function stringifyParameters($parameters) {
        $parameterString = '?';

        foreach ($parameters as $key => $value) {
            $key = urlencode($key);
            $value = urlencode($value);

            $parameterString .= "$key=$value&";
        }

        rtrim($parameterString, '&');

        return $parameterString;
    }
}

This class doesn’t do anything we haven’t seen before, except the way the options are configured (in line 60), with curl_setopt() function, to set the options with no needing to know which options are.

In order to use this class, we would only have to do something similar to this:

<?php

require_once('curl_class.php');

try {
    $curl = new CURL();

    $curl->configure('webcodegeeks.com');
    $response = $curl->execute();

    $curl->close();
} catch (Exception $exception) {
    die('An exception has been thrown: ' . $exception->getMessage());
}

Which is much more clean, readable and easy to maintain. And also more flexible, since it allows to configure any cURL option (and there is a large list of available options).

Note: cURL requests can be reused, increasing the performance. For example:

<?php

require_once('curl_class.php');

try {
    $curl = new CURL();

    $curl->configure('webcodegeeks.com');
    $response1 = $curl->execute();

    $curl->configure('webcodegeeks.com', ['s' => 'php'], 'GET');
    $response2 = $curl->execute();

    $curl->close();
} catch (Exception $exception) {
    die('An exception has been thrown: ' . $exception->getMessage());
}

The above script will work with any problem, and being more optimal than closing and opening a new cURL session for each request. In this case, the difference would probably be negligible, but for several request can suppose a significant change.

To reuse the cURL sessions, we should clean and remove the options of this before adding new ones, as done in curl_class.php in line 38, with curl_reset curl_reset() function.

5. Summary

This example has shown how we can use the cURL library in PHP scripts, for making both GET and POST requests, which have to be handled in a slightly different way. Apart from that, we have developed a class for handling cURL in a much more ordered, clean and flexible way, allowing to reuse already opened sessions, in order to improve performance.

6. Download the source code

This was a cURL example for PHP.

Download
You can download the full source code of this example here: PHPCurlGetPostExample
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button