The 'Client for URLs,' is shortly called cURL, which was originally pronounced with URL in uppercase to emphasize that it deals with URLs. It's pronounced as: "see URL."

cURL is a PHP library and command-line tool (similar to wget) that allows you to send and receive files over HTTP and FTP. You can use proxies, pass data over SSL connections, set cookies, and even get files that are protected by a login.

Role of cURL in PHP

This is a PHP module that allows PHP programs to use curl functions. When PHP's cURL support is turned on, the phpinfo() function's output will include cURL information. Before you write your first basic PHP program, you can double-check it.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

Basic Syntax for PHP Info

<?php

         php_info();

  ?>

Uses of cURL in PHP

  • cURL is a PHP extension that allows you to use the URL syntax to receive and submit data.
  • cURL makes it simple to connect between various websites and domains.
  • Obtaining a copy of a website's material. 
  • Submission of forms automatically, authentication and cookie use.

Functions of cURL in PHP

  • curl_close — Used to close the session of cURL
  • curl_error — It will return the string which represents the error for the particular current session.
  • curl_exec — After a cURL session has been created and all of the session's options have been set, the function should be named. Its sole aim is to run a predefined CURL session (given by ch).
  • curl_file_create — To create a CURLFile as object
  • curl_getinfo — Get information regarding a specific transfer
  • curl_init — To initialize the cURL session for the URL
  • curl_multi_close — Close a set of cURL handles
  • curl_pause — Pause and unpause the session connection
  • curl_reset — Reset all options of a libcurl session handle
  • curl setopt($ch, option, value) sets a cURL session option defined by the ch parameter. The value specifies the value for the specified option, and the option specifies which option to set.
  • Return page contents with curl setopt($ch, CURLOPT RETURNTRANSFER, 1). If the value is zero, no output will be returned.
  • $url is passed as a parameter to curl setopt($ch, CURLOPT URL, $url). This is the website address for your goal server and the internet URL you're looking for.
  • curl_version — This may help in getting the information for the cURL version

The Way to Download the Contents of a Remote Website to a Local File Using cURL in PHP

<!DOCTYPE html>

<html>

<body>

<?php

$url_name = "https://google.com";

  $ch_session = curl_init();

curl_setopt($ch_session, CURLOPT_RETURNTRANSFER, 1);

  curl_setopt($ch_session, CURLOPT_URL, $url);

  $result_url = curl_exec($ch_session);

  echo $result_url;

  ?>

</body>

</html>

In the above example, we are trying to show the URL information which is assigned to google.com This URL name is assigned with the variable $url_name. The session has started with the variable $ch_session.

Output 

cURL_in_PHP_1

In the above example, we are trying to view the home page of a Google website. The session was assigned with the curl_init(). This method will show the content of an assigned website into a particular curl_setopt() method. It will be saved as an html file for remote accessing.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

To Download a File from a Remote Site using cURL in PHP

If the option CURLOPT_ FILE is activated, a remote file can be downloaded to our server. For example, the following code downloads "Microsoft new launch" from Microsoft company website and saves it to our server as the microsoft_new_launch.html:

Source code

<!DOCTYPE html>

<html>

<body>

<?php

$url_name ="https://support.microsoft.com/en-in/whats-new.html";

$file_name = __DIR__ . DIRECTORY_SEPARATOR . "Microsot_new_launch.html";

$handle_session = curl_init();

$fileHandle_name = fopen($file, "w");

curl_setopt_array($handle_session,

  array(

  CURLOPT_URL       => $url_name,

   CURLOPT_FILE => $fileHandle_name,

  )

);

$data_result = curl_exec($handle_session);

curl_close($handle_session);

fclose($fileHandle_name);

?>

</body>

</html>

In the above source code, the url_name is nothing but an original resource location of the website. The handle session will manage the session details of the current website location.

We use the curl_getinfo command to get more information about the request. This command allows us to get important technical information about the response, such as the status code (200 for success), and the size of the downloaded file.

Source Code for Response Page

<?php

/*

 * vim: ts=4 sw=4 fdm=marker noet tw=78

 */

class curlDownloader

{

    private $remoteFileName = NULL;

    private $ch = NULL;

    private $headers = array();

    private $response = NULL;

    private $fp = NULL;

    private $debug = FALSE;

    private $fileSize = 0;

    const DEFAULT_FNAME = 'remote.out';

    public function __construct($url)

    {

        $this->init($url);

    }

    public function toggleDebug()

    {

        $this->debug = !$this->debug;

    }

    public function init($url)

    {

        if( !$url )

            throw new InvalidArgumentException("Need a URL");

        $this->ch = curl_init();

        curl_setopt($this->ch, CURLOPT_URL, $url);

        curl_setopt($this->ch, CURLOPT_HEADERFUNCTION,

            array($this, 'headerCallback'));

        curl_setopt($this->ch, CURLOPT_WRITEFUNCTION,

            array($this, 'bodyCallback'));

    }

    public function headerCallback($ch, $string)

    {

        $len = strlen($string);

        if( !strstr($string, ':') )

        {

            $this->response = trim($string);

            return $len;

        }

        list($name, $value) = explode(':', $string, 2);

        if( strcasecmp($name, 'Content-Disposition') == 0 )

        {

            $parts = explode(';', $value);

            if( count($parts) > 1 )

            {

                foreach($parts AS $crumb)

                {

                    if( strstr($crumb, '=') )

                    {

                        list($pname, $pval) = explode('=', $crumb);

                        $pname = trim($pname);

                        if( strcasecmp($pname, 'filename') == 0 )

                        {

                            // Using basename to prevent path injection

                            // in malicious headers.

                            $this->remoteFileName = basename(

                                $this->unquote(trim($pval)));

                            $this->fp = fopen($this->remoteFileName, 'wb');

                        }

                    }

                }

            }

        }

        $this->headers[$name] = trim($value);

        return $len;

    }

    public function bodyCallback($ch, $string)

    {

        if( !$this->fp )

        {

            trigger_error("No remote filename received, trying default",

                E_USER_WARNING);

            $this->remoteFileName = self::DEFAULT_FNAME;

            $this->fp = fopen($this->remoteFileName, 'wb');

            if( !$this->fp )

                throw new RuntimeException("Can't open default filename");

        }

        $len = fwrite($this->fp, $string);

        $this->fileSize += $len;

        return $len;

    }

    public function download()

    {

        $retval = curl_exec($this->ch);

        if( $this->debug )

            var_dump($this->headers);

        fclose($this->fp);

        curl_close($this->ch);

        return $this->fileSize;

    }

    public function getFileName() { return $this->remoteFileName; }

    private function unquote($string)

    {

        return str_replace(array("'", '"'), '', $string);

    }

}

$dl = new curlDownloader(

    'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.pexels.com%2Fsearch%2Ffree%2520download%2F&psig=AOvVaw3lIh07E0ZIZyNjqNl-JNSd&ust=1638024513705000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCKDNtfuitvQCFQAAAAAdAAAAABAD'

);

$size = $dl->download();

printf("Downloaded %u bytes to %s\n", $size, $dl->getFileName());

?>

Output

cURL_in_PHP_2.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Form Submission Using cURL in PHP

We've seen how to use the GET method of HTTP up to this stage (which is generally used to watch and download content). In order to send forms, cURL can also use the HTTP POST process.

Let’s now see how to submit a form using cURL. To do this we need to create two files. 

In this example, we are going to create the following two files - index.php, form.php.

  • Include the cURL script in the index.php file.
  • The design details of the form is enclosed in the form.php file.

In fact, form.php will be located on a remote server (although, for the sake of the example, both files may be placed on the same server). In addition, we'll use a form with three fields: first_Name, last_Name, and submit.

The form design code is

<html>

<body>

 <form method = "POST" action = "" >

  <input  name="first_Name"  type="text">

  <input  name="last_Name"  type="text">

  <input  type="submit"  name="submit"  value="שלח" >

</form>

</body>

</html>

<?php

$handle = curl_init();

$url = "https://localhost/curl/theForm.php";

$postData = array(

  'firstName' => 'Lady',

  'lastName'  => 'Gaga',

  'submit'    => 'ok'

); 

curl_setopt_array($handle,

  array(

  CURLOPT_URL => $url,

  // Enable the post response.

CURLOPT_POST   => true,

CURLOPT_POSTFIELDS => $postData,

CURLOPT_RETURNTRANSFER => true,

  )

);

 $data = curl_exec($handle);

curl_close($handle);

echo $data;

?>

With the help of the above mentioned form, we may get the details of first_name and last_name of the person using the form.

The details obtained is then be passed to the PHP response form.

cURL_in_PHP_3.

Output

cURL_in_PHP_4

To Perform Basic HTTP Authentication With cURL in PHP

In order to authenticate with cURL, the following three options need to be set:

  • CURLOPT_HTTPAUTH
  • CURLOPT_USERPWD– Through which we define the username and password.
  • CURLOPT_RETURNTRANSFER

Source Code

<?php

curl_setopt_array($handle_session,

  array(

CURLOPT_URL => $url_,

   CURLOPT_HTTPAUTH => CURLAUTH_ANY,

   CURLOPT_USERPWD  => "$user_name:$p_word",

   CURLOPT_RETURNTRANSFER   => true,

  )

);

?>

Output 

cURL_in_PHP_5.

Free Course: Programming Fundamentals

Learn the Basics of ProgrammingEnroll Now
Free Course: Programming Fundamentals

To Handle the Cookies in cURL in PHP

Cookies are used to recognize returning tourists and authenticated users on a website. In order to do this, cURL includes a method for saving cookies.

The two key choices for dealing with cookies are:

CURLOPT COOKIEJAR– Defines the file that must be used to write cookies.

CURLOPT COOKIEFILE– This variable specifies the file from which the cookies will be read.

Source Code

<?php

 $handle_session = curl_init();

 $url_name = "https://support.microsoft.com/en-in/whats-new";

 $file_name = __DIR__ . DIRECTORY_SEPARATOR . "cookie.txt";

 curl_setopt_array($handle_session,

  array(

CURLOPT_URL => $url_name,

CURLOPT_COOKIEFILE => $file_name,

   CURLOPT_COOKIEJAR  => $file_name,

CURLOPT_RETURNTRANSFER => true,

  )

);

 $data = curl_exec($handle);

 curl_close($handle);

?>

Output 

cURL_in_PHP_6

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

Using PHP's cURL extension gives us a quick and easy way to communicate with other websites, particularly APIs provided by third parties. In the next tutorial, we'll learn how to request private information on behalf of users who log in to our website using their GitHub account which will be achieved with the aid of cURL and the Github API. 

In this article, you learned about cURL with syntax and examples. To get expertise in C programming, and to further enhance your career prospects and become a specialist and a full stack technologist, you can sign up for Simplilearn’s Full Stack Web Development program. For learners, Simplilearn has made a special selection of courses available for free. Join Simplilearn for free courses on SkillUp and revolutionize your profession with certificates, specializations, and dozens of other courses. 

Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you soon.

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors