cURL in PHP

Learn via video courses
Topics Covered

cURL, or "Client for URLs," is a PHP library and command-line tool, pronounced as 'see URL.' It facilitates file transfers over HTTP and FTP, offering features like proxy support, SSL connections, and cookie handling. Comprising libcurl and curl, it's a versatile solution for developers and administrators managing data retrieval and transfer.

Installing/Configuring

To use cURL in PHP, you first need to ensure that it is installed and properly configured on your server. Here are the steps to install and configure cURL in PHP:

  1. Check if CURL is already installed on your server by running the following command in the terminal:

This will display information about the cURL extension in PHP. If it's not installed, you will need to install it.
2. Install cURL on your server by running the following command in the terminal:

This command will install the cURL extension for PHP on your server.
3. Once the installation is complete, you need to enable the cURL extension by adding the following line to your php.ini file:

Alternatively, you can enable the extension by creating a new file called curl.ini in the /etc/php/{version}/mods-available/ directory, and adding the following line to it:

  1. Finally, you need to enable the curl.ini file by creating a symbolic link to it in the /etc/php/{version}/cli/conf.d/ and /etc/php/{version}/apache2/conf.d/ directories. To do this, run the following commands in the terminal:

Replace "{version}" with the version of PHP you're using.

Explanation

After completing these steps, CURL will be installed and configured on your server, and you can start using it in your PHP applications. Follow these steps as mentioned and written above.

Uses of CURL in PHP

  • Interacting with web services and APIs:
    With cURL, developers can easily create and send HTTP requests to web services and APIs, and receive responses in a structured format. This makes it a popular tool for interacting with external services and integrating them into web applications.
  • Data scraping and crawling:
    CURL can be used to extract data from web pages and APIs, which makes it a powerful tool for web scraping and crawling. It can be used to automate tasks like data collection, monitoring, and analysis.
  • Uploading and downloading files:
    CURL supports various protocols like FTP, SFTP, and SCP, which makes it a useful tool for uploading and downloading files to and from servers. This can be useful for tasks like backups, file transfers, and content management.

Basic CURL Functions

  • curl_init():
    This function initializes a new cURL session and returns a cURL handle that can be used for further operations.
  • curl_setopt():
    This function sets various options for the cURL session, such as the URL to request, the request method, headers, authentication, and more.
  • curl_exec():
    This function executes the cURL request and returns the response as a string. It can be used to send GET, POST, PUT, DELETE, and other HTTP requests.
  • curl_close():
    This function closes the cURL session and frees up any resources used by it.
  • curl_error():
    This function returns the last error message that occurred during the cURL session.
  • curl_getinfo():
    This function returns information about the cURL session, such as the response code, headers, transfer time, and more.

Example to use all these methods:

Basic Curl Example

Explanation

In this example, we are sending a GET request to the URL https://yash.com/posts using cURL in PHP.

We start by initializing a cURL session using the curl_init() function. We then set the options for the session using curl_setopt(), which includes the URL we want to request and the CURLOPT_RETURNTRANSFER option that tells cURL to return the response as a string.

Other CURL Functions

  • curl_multi_init():
    This function initializes a new cURL multi handle that can be used for sending multiple cURL requests simultaneously.
  • curl_multi_add_handle():
    This function adds a new cURL handle to the multi handle for sending a new request.
  • curl_multi_exec():
    This function executes all the requests in the multi-handle and returns the number of handles that are still running.
  • curl_multi_getcontent():
    This function returns the content of a completed request in the multi-handle.
  • curl_multi_select():
    This function waits for activity on any of the cURL handles in the multi handle.
  • curl_multi_remove_handle():
    This function removes a completed or failed cURL handle from the multi handle.

How Does the CURL Extension Work?

The CURL extension in PHP is a wrapper around the cURL library, which is a widely-used tool for sending and receiving HTTP requests and responses. The extension provides a set of functions that allow developers to use the cURL library in PHP scripts.

When a PHP script uses the CURL extension, it initializes a new cURL session using the curl_init() function. This session can then be configured with various options using the curl_setopt() function, such as the URL to request, request method, headers, and more.

Once the session is configured, the curl_exec() function is called to execute the cURL request and return the response as a string. The response can then be processed further in the PHP script, such as by parsing it as JSON or XML.

How to Download a File from A Remote Site Using PHP cURL?

You can download a file from a remote site using PHP cURL by following these steps:

  • Initialize a cURL session using the curl_init() function.
  • Set the URL of the file you want to download using the CURLOPT_URL option with curl_setopt().
  • Set the CURLOPT_RETURNTRANSFER option to true to ensure that the file is returned as a string.
  • Set the CURLOPT_FOLLOWLOCATION option to true to follow any redirects that occur while downloading the file.
  • Set the CURLOPT_HEADER option to false to exclude any HTTP headers from the response.
  • Execute the cURL request using the curl_exec() function.
  • Save the downloaded file to a local file using the file_put_contents() function.

Here's an example code snippet that demonstrates how to download a file using PHP cURL:

Explanation

In this example, we're downloading a JPEG file from a remote site ($remoteFileUrl) and saving it to a local file ($localFilePath). The cURL session is initialized with the curl_init() function, and the URL of the remote file is set with curl_setopt(). We then set the options CURLOPT_RETURNTRANSFER, CURLOPT_FOLLOWLOCATION, and CURLOPT_HEADER as discussed earlier.

Conclusion

  • CURL is a powerful library for sending and receiving HTTP requests and responses, and the PHP cURL extension provides a convenient way for PHP developers to use the cURL library in their scripts.
  • The basic CURL functions in PHP, such as curl_init(), curl_setopt(), and curl_exec(), allow developers to configure and execute HTTP requests, and retrieve the response content.
  • The CURL extension also provides many other functions for handling more advanced features, such as sending multiple requests simultaneously with the curl_multi_* functions, and sharing data between requests with the curl_share_* functions.