php

Use of cURL Functions in PHP

cURL is a library to transfer information by using different types of protocols. The full form of cURL is the Client for URL. Two types of libraries exist for cURL. One library is curl that is a command-line tool, and it is used to send or receive files using URL. HTTP, HTTPS, FTP, FTPS, TELNET, FILE, etc., protocols are supported by curl. Another library is libcurl that is introduced by Daniel Stenberg in 1997. It is used to connect and communicate with different types of servers by using different types of protocols. All protocols of curl are supported by libcurl also. Without these protocols, libcurl supports HTTP POST, HTTP PUT, HTTPS certificates, FTP uploading, HTTP based upload, HTTP proxy tunnelling, authentication, etc. The article shows the uses of curl functions of the cURL library using PHP script.

PHP/cURL

The PHP module that is used to access the features of the libcurl library is called PHP/cURL. You have to check this is enabled or not in PHP before testing the examples of this tutorial. You can execute the phpinfo() function to check this module is enabled or not in PHP.

<?php

phpinfo();

?>

If the module is not enabled by default in PHP, then run the following commands to install and enable the php-curl on Ubuntu and restart the Apache server.

$ sudo apt install libapache2-mod-php php-curl
$ sudo service apache2 restart

Mostly used curl functions

Function Name  Purpose
curl_init() It is used to initialize a cURL session.
curl_exec() It is used to executes the started cURL session.
curl_close() It is used to close a cURL session.
curl_error() It is used to return the last error message of the current cURL session.
curl_errno It is used to return the last error number of the current cURL session.
curl_setopt() It is used to set an option for a cURL transfer.
curl_setopt_array() It is used to set multiple options for a cURL transfer.
curl_reset() It is used to reset all options of a libcurl session.
curl_pause() It is used to pause a connection.
curl_version() It is used to get the information of the cURL version.

Example 1: Retrieve the information from any URL address

Create a PHP file with the following script to retrieve the information from a particular URL address. curl_init() function is used here to initialize the cURL session for the defined URL address. The first curl_setopt() function is used to return the page content of the defined URL address. 1 is passed as the third argument value of this function to return the page content as a string value. Next, the second curl_setopt() function is used to omit the header information from the output. curl_exec() function will execute the cURL session and store the return value into $result variable that will be printed later.

<?php

//Initialize the cURL session
$ch = curl_init("https://linuxhint.com/");

//Return the page content
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Remove the header information from the output
curl_setopt($ch, CURLOPT_HEADER, 0);

//Execute the cURL session
$result = curl_exec($ch);

//Print the returned value of the website
echo $result;

//Close the cURL session
curl_close($ch);

?>

Output:

The following output will appear after running the above script. “https://linuxhint.com” is given as a URL address in the script. So, the content of this site is displayed.

Example 2: Write the cURL output in a file

In the previous example, the output of the script is shown in the browser. But you can store the return value of any URL address in a file also by using cURL. Create a PHP file with the following script to take the URL address by using an HTML form and initialize the cURL session for that URL and store the page content into a text file rather than displaying it in the browser. CURLOPT_FILE option is used in curl_setopt() function to store the output after executing the cURL session into output.txt file. If the invalid URL address is submitted by the form, then the error information will be written in the file in place of the page content.

<html>
<head>
    <title>cURL Example</title>
</head>
<body>
    <form method="get" action="#">
        <p>Enter an URL Address</p>
        <p><input type="text" name="url" /></p>
        <p><input type="submit" name="submit" value="Submit">
    </form>
</body>
</html>

<?php

//Check the submit button is pressed or not
if(isset($_GET['url']))
{
    //Check the url is empty or not
    if($_GET['url'] != "")
    {
        //Set the URL value
        $url = $_GET['url'];

        //Initialize the cURL session
        $ch = curl_init($url);

        //Open file handler to write in a text file
        $fh = fopen("output.txt", "w");

        //Set option for writing the output in aa file
        curl_setopt($ch, CURLOPT_FILE, $fh);

        //Include header information in a file
        curl_setopt($ch, CURLOPT_HEADER, 1);

        //Execute the cURL session
        curl_exec($ch);

        //Check for any cURL error
        if(curl_error($ch)) {
            $error =  curl_errno($ch)." : ". curl_error($ch);
            fwrite($fh, $error);
        }

        echo "The output of the cURL session has been written in <b>output.txt</b>
        file"
;

        //Close the cURL session
        curl_close($ch);
        //Close the file
        fclose($fh);
    }
    else
    {
        echo "No URL address is set.";
    }
}

?>

Output:

The following form will be appeared after running the script. Here, a valid URL address is given as the URL address.

The following output will appear after running the pressing the submit button.

Example 3: Set cURL option using the array

If you want to set multiple cURL options at the time of executing the cURL session, then you have to use the curl_setopt_array() function. Create a PHP file with the following script to know the use of this function. Two cURL options are set using an array variable, and this variable is passed as an option variable of the curl_setopt_array() function.

<?php

//Define the array of options
$defaults = array(
CURLOPT_URL => 'http://example.com/',
CURLOPT_POST => true
);

//Initialize the cURL session
$ch = curl_init();

//Return the page content based on option array
curl_setopt_array($ch, $defaults);

//Print the returned value
echo curl_exec($ch);

?>

Output:

The following output will appear after running the script. “http://example.com” is given as a URL address in the script.

Conclusion

The simple uses of cURL in PHP are shown in this tutorial by using various examples. Many built-in cURL functions exist in PHP to do different types of tasks. This tutorial will help the readers to know the basic uses of cURL in PHP.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.