Hurry Up! Refer new customers to Codentheme and receive  10%  of their each purchase. Become an affiliate now
cURL in PHP: A Comprehensive Tutorial

cURL in PHP: A Comprehensive Tutorial

cURL is a powerful tool that can handle all sorts of data-related tasks in PHP development. What’s cool about cURL?

Need to grab information from a website? CURL can do that.

Want to upload files to a server? CURL has got you covered.

Need to make API requests and interact with different systems? CURL can handle that too.

In this comprehensive tutorial, we will explore what cURL is and how it works. In addition, we will provide detailed examples to ensure you fully understand cURL concepts.

The tutorial on cURL in PHP will help you develop your PHP programming skills.  

Let’s start.

What is cURL?

cURL is an easy-to-use command-line tool and a library for transferring data over protocols.

It has gained immense popularity and earned developers’ trust. At its core, cURL excels in sending and receiving data using URL syntax. Its strength lies in its extensive protocol support.

cURL lets developers interact with various systems and services effortlessly.

Significance in PHP Development.

cURL is an invaluable resource for PHP development due to its versatility and robustness.

PHP developers can interact with remote servers, fetch data from APIs, and perform actions such as making HTTP requests, handling cookies, and managing file transfers.

  • API Integration. 

cURL is standard to integrate with web services and APIs. PHP developers can send HTTP requests and retrieve responses. They can easily access and work with data from external sources like social media platforms, payment gateways, and weather services.

  • Data Retrieval.

cURL can fetch data from remote servers. PHP developers can retrieve web pages in XML, JSON, or other data formats. It provides functionalities to set request headers, handle cookies, follow redirects, and perform HTTP requests (GET, POST, PUT, DELETE, etc.).

  • Web Scraping.

With cURL, developers can fetch and extract data from web pages programmatically. It’s handy for data aggregation, content monitoring, and extracting specific information from websites.

  • File Transfer. 

cURL supports different file transfer protocols such as FTP, FTPS, SFTP, SCP, and more. Therefore, PHP developers can easily transfer or interact with file hosting services.

  • Authentication: 

 cURL supports different authentication mechanisms, including basic authentication, OAuth, and custom authentication methods. As a result, PHP developers can authenticate for accessing protected resources or interfacing with APIs that require authentication.

  • Error Handling and Debugging.

cURL allows developers to handle errors gracefully. They can troubleshoot connectivity issues when making HTTP requests. 


Installing and Enabling cURL in PHP: A Step-by-Step

First, go to the cURL website. Here you can download precompiled cURL binaries that match your Windows version and PHP installation (32-bit or 64-bit). 

After the download is complete, you will need to extract the downloaded file.

Select a location on your computer to save the extracted files. For example, you can extract them to C:\curl.

Then update your PHP configuration.

Locate your PHP installation directory and look for the php.ini file. Open it in a text editor.

In the php.ini file, use the search function to find the line that says “;extension=curl” (without the semicolon). 

Remove the semicolon at the beginning of the line to uncomment it. This will enable the cURL extension in PHP.

To ensure that PHP can find the cURL binary, you must set the cURL path in your system’s PATH environment variable.  Here’s how you can do it.

  • Open the Control Panel. Click on > System and Security > System > Advanced system settings. 
  • Look for the “Environment Variables” button and click on it. 
  • In the “System Variables” section, find the “Path” variable and select “Edit”. 
  • Add ;C:\curl (or the path where you extracted cURL) to the existing values. 

Make sure to separate it from the previous entry with a semicolon (;). Click “OK” to save your changes.

The web server must be restarted for the changes to take effect. This can be Apache, Nginx, or whatever server you use. After restarting the server, cURL will be enabled in your PHP environment.  

Now it’s time to verify that it’s working correctly in your PHP environment. Here’s how you can do it.

  1. Create a new PHP file and name it “curl_test.php” for example. Open the file in a text editor.
  2. Add the following code to the curl_test.php file.
<?php
phpinfo();
?>
  1. Save the file and access it through your web server. For example, you can access it by navigating to http://localhost/curl_test.php.
  2. If everything is set up correctly, you should see a comprehensive PHP information page.
  3. To confirm that cURL is installed and enabled, use your browser’s search function on the PHP info page to find the term “curl”. If cURL is properly installed and enabled, you should see a dedicated section displaying cURL-related information.

That’s it! You have successfully installed and enabled cURL in your PHP environment.


Uses of cURL in PHP.

cURL is an incredibly versatile tool in PHP that opens up a world of possibilities for web developers.

  1. Connecting between Websites and Domains: cURL allows PHP developers to establish connections between different websites and domains effortlessly. You can utilize cURL to fetch data from external APIs, retrieve information from remote servers, or interact with web services. This enables seamless integration between your PHP application and external systems, facilitating data exchange and communication.
  1. Fetching Website Content: With cURL, you can easily retrieve website content programmatically. Whether you need to extract specific data from a web page, scrape information for analysis, or build web crawlers, cURL provides the means to fetch the HTML content of a webpage. This empowers you to automate data retrieval processes and build robust web scraping applications.
  1. Submitting Forms: When dealing with forms on websites, cURL becomes invaluable. You can use cURL to simulate form submissions, sending POST or GET requests with form data to a target website. This is particularly useful when automating form submissions, testing web applications, or building web automation scripts. cURL enables you to interact with forms programmatically, saving you time and effort.
  1. Handling Authentication and Cookies: cURL is well-equipped to handle various authentication mechanisms and cookies. You can authenticate requests using Basic Authentication, Digest Authentication, or OAuth, depending on the requirements of the target website or API. Additionally, cURL allows you to manage cookies, ensuring that sessions are maintained across multiple requests. This is crucial when interacting with websites that require authentication or rely on session-based functionality.

In Real-World Web Applications.

Let’s explore a few dynamic web development where cURL can be beneficial:

  1. API Integration: You can use cURL to communicate with external APIs, such as social media APIs or payment gateways, to fetch data, post updates, or process transactions.
  1. Data Aggregation: Suppose you need to gather data from multiple sources and consolidate it into a central database. cURL enables you to fetch data from various websites or APIs and store it in your system seamlessly.
  1. Web Scraping: If you want to extract specific data from websites for analysis or research purposes, cURL provides the tools to scrape web content efficiently and reliably.
  1. Automated Testing: When conducting automated tests for web applications, cURL allows you to simulate user interactions, submit forms, and validate responses, making it a valuable asset for building test automation scripts.

functions of cURL in PHP.

curl_close: The curl_close function is used to close a cURL session.It deallocates the related resources and frees up memory. curl_close is important to invoke this function once you are done utilizing a cURL handle to prevent any resource leaks.

Here’s an example.

// Initialize cURL session
$curl = curl_init();

// ...

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

curl_exec: The curl_exec function executes a cURL session and returns the output. It performs the request defined by the options set using curl_setopt.  The response can be retrieved as a string or written directly to a file. This function is important for making HTTP requests and fetching data from remote servers.

Here’s an example:

// Initialize cURL session
$curl = curl_init();

// Set options and perform request
curl_setopt($curl, CURLOPT_URL, "https://example.com");
curl_exec($curl);

// Check for errors
if (curl_error($curl)) {
    $error = curl_error($curl);
    // Handle the error
    echo "cURL Error: " . $error;
}

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

curl_exec: The curl_exec function executes a cURL session and returns the output. It performs the request defined by the options set using curl_setopt.  The response can be retrieved as a string or written directly to a file. This function is important for making HTTP requests and fetching data from remote servers.

Here’s an example:

// Initialize cURL session
$curl = curl_init();

// Set options and perform request
curl_setopt($curl, CURLOPT_URL, "https://example.com");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Return the response instead of printing it
$response = curl_exec($curl);

// Process the response
echo $response;

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

curl_file_create: The curl_file_create function creates a CURLFile object. It represents a file to be uploaded via cURL by setting its name, MIME type, and other relevant information. It is commonly used when uploading files to a server.

Here’s an example:

// Create a CURLFile object for the file to be uploaded
$file = curl_file_create("/path/to/file.jpg", "image/jpeg", "myfile.jpg");

// Set the file to be uploaded as a POST field
curl_setopt($curl, CURLOPT_POSTFIELDS, ["file" => $file]);

// ...

curl_getinfo: The curl_getinfo function retrieves information about the last cURL transfer. It returns an array or a specific value depending on the information requested. This function provides various details such as the URL, response code, content type, transfer time, and more. It’s valuable for analyzing and understanding the outcome of a cURL request.

Here’s an example:

// Initialize cURL session
$curl = curl_init();

// Set options and perform request
curl_setopt($curl, CURLOPT_URL, "https://example.com");
curl_exec($curl);

// Get information about the transfer
$info = curl_getinfo($curl);

// Access specific information
echo "Response Code: " . $info['http_code'];

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

curl_init: The curl_init function initializes a new cURL session. It returns a cURL handle that is used in subsequent cURL operations. This function allows you to customize various options such as URL, request method, headers, and more before executing the request.

Here’s an example:

// Initialize cURL session
$curl = curl_init();

// Set options and perform request
curl_setopt($curl, CURLOPT_URL, "https://example.com");
curl_exec($curl);

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

curl_multi_close: The curl_multi_close function closes a set of cURL handles previously opened with curl_multi_init.It releases the associated resources and memory. Properly closing the handles is essential to prevent resource leaks and ensure efficient memory management.

Here’s an example:

// Initialize cURL multi-handle
$multiHandle = curl_multi_init();

// ...

// Close the cURL multi-handle
curl_multi_close($multiHandle);

curl_pause: The curl_pause function pauses or unpauses a cURL handle within a multi-handle. Pausing a handle temporarily suspends the transfer, allowing you to perform other operations before resuming it. This function is valuable when you need to control the timing and sequencing of multiple cURL requests in a multi-handle process.

Here’s an example:

// Pause a cURL handle
curl_pause($curlHandle, CURLPAUSE_SEND);

// ...

// Resume the cURL handle
curl_pause($curlHandle, CURLPAUSE_CONT);

curl_reset: The curl_reset function resets a cURL handle to its default state. It clears all the options and parameters previously set for that handle. It’s useful when you want to reuse a cURL handle for multiple requests without carrying over any previous configurations. This function allows you to reuse the same handle for multiple requests.

Here’s an example:

// Initialize cURL session
$curl = curl_init();

// Set options and perform request
curl_setopt($curl, CURLOPT_URL, "https://example.com");
curl_exec($curl);

// Reset the cURL handle
curl_reset($curl);

// Set options for the next request
curl_setopt($curl, CURLOPT_URL, "https://another-example.com");
curl_exec($curl);

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

curl_setopt: The curl_setopt function is used to set various options for a cURL session. It allows you to set request headers, specify the request method, configure SSL options, handle cookies, and more. This function gives you flexibility and control over the cURL request to meet specific needs.

 Here’s an example:

// Initialize cURL session
$curl = curl_init();

// Set options
curl_setopt($curl, CURLOPT_URL, "https://example.com");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// ...

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

curl_version: The curl_version function shares realated information about the cURL version installed on the server. This function is useful for checking the capabilities and features of the installed cURL library.

Here’s an example:

// Get cURL version information
$version = curl_version();

// Access specific information
echo "cURL Version: " . $version['version'];

// ...

How to fetch and display the contents of a remote website using cURL in PHP? 

Let’s walk through a step-by-step example of how to fetch and display the contents of a remote website using cURL in PHP. 

Step 1: Initialize the cURL session.

First, we need to initialize the cURL session using the curl_init function. This function returns a cURL handle for subsequent cURL operations. 

The code is as follows:

// Initialize cURL session
$curl = curl_init();

Step 2: Set options for the request.

Next, you are required to set options for the cURL request using the curl_setopt function. And put the URL of the remote website you want to fetch. 

The code is as follows:

// Set the URL of the remote website
curl_setopt($curl, CURLOPT_URL, "https://example.com");

Step 3: Set option to return the response.

Now, Set the CURLOPT_RETURNTRANSFER option to true to prevent the response from being displayed directly and returned from curl_exec. It allows you to save the response in a variable for further processing. 

The code is as follows:

// Set the option to return the response
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

Step 4: Execute the cURL request.

After setting the options, use the curl_exec function to execute the cURL request. It will send a request to the remote website to retrieve the HTML content. 

The code is as follows:

// Execute the cURL request and store the response
$response = curl_exec($curl);

Step 5: Check for errors and display the result.

After executing the request, always check for errors using the curl_error function. If there are no errors, you can then display the retrieved HTML content. 

The code is as follows:

// Check for errors
if (curl_error($curl)) {
    $error = curl_error($curl);
    // Handle the error
    echo "cURL Error: " . $error;
} else {
    // Display the HTML content
    echo $response;
}

Step 6: Close the cURL session.

Finally, use the curl_close function to close the cURL session and release associated resources. 

The code is as follows:

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

* The HTML content will be stored in the $response variable, and you can process it or display it as needed.


Form Submission using cURL in PHP.

First, let’s create a sample HTML form to use for demonstration purposes. The below code creates a simple form with two input fields for “name” and “email address” and a submit button.

<form action="submit.php" method="POST">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  
  <input type="submit" value="Submit">
</form>

Our next step will be to create a PHP file, named submit.php, that will handle the submission of the form. In this file, we’ll use cURL to send a POST request with the form data.

Here’s an example of how to set it up:

<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // Get the form data
  $name = $_POST["name"];
  $email = $_POST["email"];

  // Initialize cURL session
  $curl = curl_init();

  // Set the URL of the target script or endpoint that will process the form submission
  curl_setopt($curl, CURLOPT_URL, "https://example.com/process-form");

  // Set the request method to POST
  curl_setopt($curl, CURLOPT_POST, true);

  // Set the form data to be sent
  curl_setopt($curl, CURLOPT_POSTFIELDS, [
    "name" => $name,
    "email" => $email
  ]);

  // Execute the cURL request
  $response = curl_exec($curl);

  // Check for errors
  if (curl_error($curl)) {
    $error = curl_error($curl);
    // Handle the error
    echo "cURL Error: " . $error;
  } else {
    // Display the response
    echo "Form submitted successfully!";
  }

  // Close the cURL session
  curl_close($curl);
}
?>

 In the code above, we’ve set the target URL to “https://example.com/process-form“.

*Change this URL to the actual URL that will process the form submission. It can be a URL within your own application or an external API endpoint.

Make sure the form’s action attribute points to the correct file path to trigger the submission and send the form data to submit.php. In the above example the action is set to submit.php. We assume the form and the submit.php file are in the same directory. 

When the form is submitted, the data will be sent as a POST request to the specified script or endpoint. You can handle the form data in the PHP file and perform further processing or store it in a database.


How to perform Basic HTTP authentication using cURL in PHP?

Basic HTTP authentication is a simple method of authentication. It involves sending a username and password in the HTTP headers.

To understand this, we’ll walk through an example to set up and authenticate using cURL.

<?php
// URL of the protected resource
$url = "https://example.com/protected-resource";

// Username and password for authentication
$username = "your_username";
$password = "your_password";

// Initialize cURL session
$curl = curl_init();

// Set the URL
curl_setopt($curl, CURLOPT_URL, $url);

// Enable HTTP authentication
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

// Set the username and password
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);

// Set the option to return the response
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// Execute the cURL request
$response = curl_exec($curl);

// Check for errors
if (curl_error($curl)) {
    $error = curl_error($curl);
    // Handle the error
    echo "cURL Error: " . $error;
} else {
    // Display the response
    echo "Response: " . $response;
}

// Close the cURL session
curl_close($curl);
?>

The example above has the following steps:

Please enter the URL:

Set the URL of the protected resource you want to access. Replace “https://example.com/protected-resource” with the actual URL.

Set your username and password.

Replace “your_username” and “your_password” with your desire credentials. These are used for authentication.

Initialize a cURL session.

Initialize the cURL session using curl_init() .

Enable HTTP authentication.

To enable basic HTTP authentication, set the CURLOPT_HTTPAUTH option to CURLAUTH_BASIC.

Set your username and password.

Set up the username and password using the CURLOPT_USERPWD option. It should be in the format “username: password”.

Set options for returning responses.

Set the CURLOPT_RETURNTRANSFER option to true to store the response in a variable instead of displaying it directly.

Execute a cURL request.

Use curl_exec() Executes a cURL request and saves the response in the $response variable. Check for errors and display answers.

Check for errors.

To check for errors, use curl_error(). If there are no errors, display the response.

Close the cURL session.

Close the cURL session using curl_close() . 


How to enable and handle cookies using cURL in PHP?

Cookies are essential for maintaining state and session information between multiple HTTP requests. 

The below example explains how to handle cookies in cURL when making requests in PHP.

<?php
// URL to fetch with cookies
$url = "https://example.com/protected-resource";

// Initialize cURL session
$curl = curl_init();

// Enable cookie handling
curl_setopt($curl, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($curl, CURLOPT_COOKIEFILE, 'cookies.txt');

// Set the URL
curl_setopt($curl, CURLOPT_URL, $url);

// Set the option to return the response
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// Execute the cURL request
$response = curl_exec($curl);

// Check for errors
if (curl_error($curl)) {
    $error = curl_error($curl);
    // Handle the error
    echo "cURL Error: " . $error;
} else {
    // Display the response
    echo "Response: " . $response;
}

// Close the cURL session
curl_close($curl);
?>

In the example above, we have the following steps:

  1. Specify the URL: Set the URL of the resource you want to access. Replace “https://example.com/protected-resource” with the actual URL.
  2. Initialize cURL session: Initialize the cURL session using curl_init().
  3. Enable cookie handling: Use CURLOPT_COOKIEJAR to specify the file where cookies will be stored. In this example, we set it as ‘cookies.txt‘. The file path can be customized based on your needs. CURLOPT_COOKIEFILE is used to specify the file from which cookies will be read for subsequent requests.
  4. Set the URL: Set the URL using CURLOPT_URL.
  5. Set the option to return the response: Set CURLOPT_RETURNTRANSFER to true to store the response in a variable instead of displaying it directly.
  6. Execute the cURL request: Use curl_exec() to execute the cURL request and store the response in the $response variable.
  7. Check for errors and display the response: Use curl_error() to check for any errors. If there are no errors, display the response.
  8. Close the cURL session: Close the cURL session using curl_close().

By following these steps, you can handle cookies in cURL requests using the CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE options. The CURLOPT_COOKIEJAR option specifies the file to store the cookies in, and CURLOPT_COOKIEFILE reads the cookies from the specified file for subsequent requests. This way, you can maintain session information and handle cookies seamlessly when using cURL in PHP.

Related Posts

How to Use Try Catch in PHP for Effective Debugging.
How to Use Try Catch in PHP for Effective Debugging.

Programming errors are a part of all software development. PHP is no exception! Handling errors…

Read More
Ternary Operator in PHP: Simplifying Your Code
Ternary Operator in PHP: Simplifying Your Code

Conditional expressions are an essential part of programming. They allow developers to make decisions about…

Read More