Life StyleTechWorld

What Is CURL in PHP: Uses, Basic Concepts and Authentication

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.

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 %sn”, $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!

Leave a Reply

Your email address will not be published.