What is cURL Used For | 2023 PHP Code Examples & Alternatives

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

In this article, we will learn what cURL is and why we use it in PHP. We will discuss the cURL HTTP GET request, cURL HTTP POST request, cURL HTTP PUT request and cURL HTTP DELETE request, with PHP examples. We will also discuss the advantages and disadvantages of using cURL in PHP and also the alternatives to cURL. 

php curl examples

Table of Contents

In this article, we will cover the following topics.

  1. What is a cURL Library?  
  2. Why do we Use cURL in PHP?
  3. Is cURL installed by default with PHP?
  4. cURL HTTP Verbs used in PHP.
  5. cURL HTTP GET Request PHP Example.
  6. cURL HTTP POST Request PHP Example.
  7. cURL HTTP PUT Request PHP Example.
  8. cURL HTTP DELETE Request PHP Example.
  9. What are the advantages and disadvantages of using cURL in PHP?
  10. Alternatives to cURL in PHP.
  11. Using cURL in PHP Explored.

What is the cURL Library?

The cURL library is a c-based library that allows web applications to make HTTP requests. Many languages like PHP provide wrappers around the extension and use it extensively. The cURL library was created by famous developer Daniel Stenberg. It was first released in 1996.

CURL stands for client URL. It allows users to fetch data from APis in PHP and send and receive data through the URL. It makes communication easy between different websites and domains. We use cURL to make requests using different protocols.

The PHP cURL library supports multiple protocols, including HTTP, HTTPS, FTP, MQTT, etc. Curl is accessible on Windows, Linux, and Mac, making it the go-to choice for developers across all platforms.

Why do we Use cURL in PHP?

cURL is used to make requests using different protocols in command lines or scripts to transfer data. It is also used in cars, television sets, routers, printers, audio equipment, mobile phones, tablets, settop boxes, and media players. It is the Internet transfer engine for thousands of software applications in over ten billion installations. cURL is used daily by virtually every Internet-using human on the globe.

We should use cURL in PHP due to the following benefits

  • In PHP, the cURL allows you to use the URL syntax to receive and submit data.
  • cURL makes it easy for you to connect between various websites and domains.
  • It can also obtain a copy of a website’s material. 
  • Submission of forms automatically, authentication and cookie use.

Is cURL installed by default with PHP?

It depends on your host and server. Many Linux servers & hosts come with PHP & cURL installed by default, but this isn’t guaranteed. You will need to run a few commands on your server to confirm whether cURL is properly installed. We wrote a complete article on testing & installing cURL from the server.

To learn if cURL is installed by default with PHP, read our article in detail 

And if you want to install cURL libraries for PHP on AWS EC2 check out our article How to Install cURL for PHP on AWS Amazon Linux EC2

cURL HTTP Verbs used in PHP

cURL uses all of the standard HTTP methods: – GET,  PUT, POST, and DELETE. You can also send OPTIONS, HEAD and others that you may need in rare occasions.

  • GET retrieves a resource from a server, such as a file, information, or an image.
  • POST is used to send information to the server.
  • PUT can be used to create or update a resource. This could be used to create or update a database record or update a file’s contents.
  • DELETE is used to delete a resource, such as a database entry.
php curl examples

Let’s discuss each of them in detail along with PHP examples.

cURL HTTP GET Request PHP Code Example

Sending a cURL get request in PHP requires that you have cURL installed correctly on the server and that you are following the right procedural code. cURL will use the HTTP GET method by default when using the curl_exec function.

PHP cURL comes with a bunch of functions – see the documentation.

Some functions are fundamental for the lifecycle of a typical cURL request in PHP.

curl_init(); //Initializes a cURL session and returns a cURL handler.
curl_setopt(); //Sets up the options for the cURL session.
curl_exec(); //Executes the cURL session.
curl_close(); //Closes the session and deletes the variable (recommended use)

Here’s a code of the example that performs a basic cURL GET request in PHP.

$url = "https://jsonplaceholder.typicode.com/posts/1";
 
$curl = curl_init($url); //Initializes a cURL session and returns a cURL handler.
 
$response = curl_exec($curl); //Executes the cURL session.
 
curl_close($curl); //Closes the session and deletes the variable (recommended use)
 
echo $response;
Read our article to learn more about How to Send a cURL GET Request:

cURL HTTP POST Request PHP Code Example

A typical cURL post request would have a URL and a payload with headers and data. The cURL library will make an HTTP POST request to the specified URL. The URL points to the server and picks the request here.

Here’s a featured snippet code of the example that performs a basic POST cURL request with a body from a file in PHP.

<?php
 
//Initialise the cURL var
$curl = curl_init();
 
//Create a POST array with the file in it
$fileData = file_get_contents("file_1.json");
 
//All options in an array
$options = [
   CURLOPT_URL => 'https://fir-fuelingphp-default-rtdb.firebaseio.com/user.json',
   CURLOPT_POST => true,
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_HTTPHEADER => ["Accept: application/json", "Content-Type: application/json"],
   CURLOPT_POSTFIELDS => $fileData
 
];
 
//Set the Options array.
curl_setopt_array($curl, $options);
 
// Execute the request
$response = curl_exec($curl);
 
//If error occurs
if (curl_errno($curl)) {
  echo "CURL ERROR - " . curl_error($ch);
}
 
//If no errors
else {
  echo $response;
}
 
//Close to remove $curl from memory
curl_close($curl);
?>

cURL HTTP PUT Request PHP Code Example

The HTTP cURL PUT method is one of the commonly used methods of the HTTP protocol. We call the HTTP PUT request method when we need to update a resource. It creates a new resource or replaces an existing one with a request. If the resource already exists in URO, PUT replaces it. In the case of no resource, PUT creates a new one. The HTTP PUT is idempotent and is not cacheable.

We use the following code to make a simple HTTP cURL PUT request.

<?php


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


// Set the URL, request method (PUT), and other options
curl_setopt($ch, CURLOPT_URL, "https://fuelingphp.com/");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array("field1" => "value1", "field2" => "value2")));


// Execute the request and get the response
$response = curl_exec($ch);


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


?>

The above code makes a PUT request to the specified URL with the specified data. We can also add some additional options to customize the request, such as setting HTTP headers or enabling SSL.

To PUT a file onto the server, we use the following code.

<?php


//The URL that we want to send a PUT request to.
$url = 'https://fuelingphp.com/';


//Initiate cURL
$ch = curl_init($url);


//We use the CURLOPT_PUT option to tell cURL that
//this is a PUT request.
curl_setopt($ch, CURLOPT_PUT, true);


//We want the result / output returned.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


//Our fields.
$fields = array("id" => 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));


//The path of the file that we want to PUT
$filepath = 'Test_File.txt';


//Open the file using fopen.
$fileHandle = fopen($filepath, 'r');


//Pass the file handle resorce to CURLOPT_INFILE
curl_setopt($ch, CURLOPT_INFILE, $fileHandle);


//Set the CURLOPT_INFILESIZE option.
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($filepath));


//Execute the request.
$response = curl_exec($ch);


echo $response;

The above code makes a PUT request to the specified URL with the specified file. We opened the given file in the above PHP code before passing its file handle to cURL using the CURLOPT_INFILE option. We also specified the file size in bytes by using the CURLOPT_INFILESIZE option.

cURL HTTP DELETE Request PHP Code Example

The HTTP cURL DELETE method deletes a resource from the server. The HTTP cURL DELETE method asks the server to delete the resource specified in the Request-URI. Unlike GET and HEAD requests, the DELETE requests can change the server state. 

The DELETE method is idempotent, meaning that sending the same HTTP DELETE request multiple times will have the same effect on the server and will not additionally affect the state or cause additional side effects.

The following code example demonstrates sending a DELETE request with PHP using cURL.

<?php


// Set up cURL
$ch = curl_init('https://fuelingphp.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


// Set up a DELETE request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");


// Set up data for DELETE request (if applicable)
$data = array('key1' => 'value1', 'key2' => 'value2');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));


// Send the request
$response = curl_exec($ch);


// Checking for errors
if($response === false) {
    die(curl_error($ch));
}


// Decode the response
$responseData = json_decode($response, true);


// Print the response data
print_r($responseData);

The above code sends a DELETE request to the specified URL with the specified data (if applicable). The response from the server will be saved in the $response variable and can be decoded and printed, as shown in the example.

Note that the server you send the request to must be set up to handle DELETE requests and correctly process the data.

What are the advantages and disadvantages of using cURL in PHP?

Technically, you must use cURL if you want to send HTTP requests via PHP, so it’s well-tested, stable, and not going anywhere anytime soon. The primary disadvantage, on the other hand, is that it’s hard to debug and not object-oriented. In most cases, you should use the Guzzle composer package or create your own wrapper class around cURL.

Advantages.

  • cURL lets you download the contents of a remote website to a local file in PHP.
  • We can also download files from a remote site using cURL in PHP.
  • We can also send Google forms using cURL in PHP.
  • We can also perform basic HTTP Authentication with cURL in PHP
  • We can also handle the cookies in cURL in PHP.

Disadvantages.

  • Since PHP/cURL uses libcurl and it requires cURL to be installed, the command line tool. If you are using shared hosting, you might need more control to install software packages.
  • PHP/cURL provides many options to work with curl, as its official document shows. It needs to be shorter to work with. It does not provide the most pleasant API.
  • Unit testing is a pain if you are using PHP/cURL. There is no box support for unit testing.

Alternatives to cURL in PHP

The following are the alternatives to cURL in PHP.

Guzzle an alternative to cURL in PHP

Guzzle is a PHP HTTP client package installed via composer, making sending HTTP requests very easy. Integrating with different web services is fairly trivial and provides an object-oriented API to use. 

The best thing about Guzzle is that it can also be used with any HTTP handler like cURL, socket, and PHP’s stream wrapper. Guzzle, by default, uses cURL as an HTTP handler. You only need to configure an HTTP handler to use a different method of sending requests.

cURL is a great HTTP client, but Guzzle will also continue to use it by default when it is available. It is rare, but some developers need cURL installed on their systems or run into version-specific issues. By allowing swappable HTTP handlers, Guzzle is now much more customizable and able to adapt to the needs of more developers.

Advantages of Guzzle over cURL.

  • Guzzle provides an easy user interface.
  • Guzzle uses various kinds of HTTP clients.
  • It also allows us the facility of asynchronous and synchronous requests.
  • Guzzle has built-in unit testing support, which makes it easy to write unit tests for the app and mock the HTTP requests.

The file_get_content() Function an alternative to cURL

Another alternative to cULR is the file_get_contents(). It is a PHP function that gets the contents of a file. Unlike cURL, it doesn’t require any configuration so you can call it as so:

$data = file_get_contents('http://url_to/get_contents/from');

It reads the entire file source or part of it and returns it as PHP string data. It is the most widely used function among other dedicated functions used for PHP file read.

But there is one disadvantage of using this function some web hosts block file_get_contents() function. Using this function is perfect for quick data retrieval.

Using cURL in PHP Explored

cURL is a very powerful tool for internet protocol transfers. Mastering its use is a challenge, but it can become irreplaceable in any developer’s toolkit. Using PHP’s cURL extension gives you a quick and easy way to communicate with other websites, particularly APIs provided by third parties.

This article explains what a cURL is and why we use it. It also explains HTTP cURL GET request, cURL POST request, cURL PUT request and cURL DELETE request, along with a PHP example. 

This article also focuses on the advantages and disadvantages of using cURL in PHP, and we hope you find this article helpful.

Continue Learning About cURL

This article is part of a more extensive series on using cURL in PHP. Feel free to browse through the articles to dig deeper into the topic.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.