How to Use cURL in PHP

Today, we’re going to explore the cURL extension in PHP which allows you to make HTTP requests from your code.

Often you need to communicate with external websites in your day-to-day PHP development. Whether it’s calling third party REST APIs to fetch data or downloading resources from the external website, you want a library which allows you to do it effortlessly.

In PHP, there are different ways you can use to connect and communicate with different types of servers. One of the easiest ways is to use the file_get_contents function to read remote files. On the other hand, you can also use sockets to implement client-server communication. In this article though, we’re going to discuss the cURL extension in detail with real-world examples.

cURL stands for client URLs and it’s a library which allows you to send and receive information with the URL syntax. In fact, it leverages the libcurl library, created by Daniel Stenberg, which allows you to connect and communicate to many different types of servers with many different types of protocols. Apart from HTTP and HTTPS, the libcurl library also supports protocols like FTP, Gopher, Telnet, DICT, File, and LDAP.

From the next section onwards, we’ll go through a couple of real-world examples to demonstrate how you can use cURL functions in PHP.

Real-World Examples

In this section, we’ll build real-world examples to demonstrate various cURL functions in PHP.

How to Download Files Using cURL in PHP

Reading or downloading remote files is one of the most common use-cases for cURL. This is accomplished by a cURL GET request, which we’ll discuss in this section.

Go ahead and create the curl_read_file.php file with the following contents.

In the above example, we’ve used cURL functions to read the home page of the example.com domain. Let’s go through the important snippets to understand how it works.

Firstly, we’ve used the curl_init function to initialize a new cURL session. The $curlHandle variable holds a cURL handle, which we can use to set various options for cURL transfer with the help of the curl_setopt function.

When you’re working with cURL, the curl_setopt function is the one you will mostly deal with, since it allows you to initialize various CURLOPT_* request options. The curl_setopt function takes three arguments: a cURL handle, the CURLOPT_XXX option and the value of  the CURLOPT_XXX option.

Next, we’ve used the CURLOPT_URL option to set the request URL to example.com with the curl_setopt function. Further, we’ve set the CURLOPT_RETURNTRANSFER option to TRUE as we want to initialize the response into the $responseData variable. If we don’t set it to TRUE, the response will be displayed directly on the screen. Lastly, we’ve set the CURLOPT_HEADER option to FALSE to skip the header information in output.

Finally, we’ve used the curl_exec function to execute the cURL request. If everything goes fine, the $responseData variable should contain the source of the home page of example.com.

How to Post Data Using cURL in PHP

In this section, we’ll see how to post data with cURL.

Let’s create the curl_post_example.php file with the following contents.

In the above example, we assume that we need to submit a request with the HTTP POST method. In fact, it works similar to submitting a form with the POST method.

The $fields variable holds an array of values that we need to submit as a POST data. Next, we’ve used the http_build_query function to prepare a URL-encoded querystring.

Next, we’ve set the CURLOPT_POST option to TRUE to set the request method to HTTP POST. Further, we need to use the CURLOPT_POSTFIELDS option to set the POST data that we want to submit along with the request.

Finally, we’ve used the curl_exec function to execute the cURL request. So in this way, you can make a cURL POST request.

How to Post JSON Data Using cURL in PHP

More often than not, you need to submit JSON data in a cURL POST request. In this section, we’ll see how you can submit JSON data with the POST method in a cURL request.

Since it’s a POST request, let’s revise the example which we’ve just discussed in the previous section. Go ahead and create the curl_post_json.php file with the following contents.

Although it may look similar to the example in the previous section, the important thing is that we’ve used the json_encode function to create a JSON string from the $fields array.

Next, we’ve used the CURLOPT_HTTPHEADER option to set the Content-Type header to application/json to inform the API server that we’re sending JSON data. The Content-Type header is useful to post data in different formats. For example, if you wanted to send XML data, you would have to set the Content-Type header to application/xml.

Except that, it’s pretty much the same as that of the regular POST request. So in this way, you can post different types of data by setting the appropriate Content-Type header. If you don’t set the Content-Type header, it will use application/x-www-form-urlencoded as the default value.

How to Upload Files Using cURL in PHP

In this section, we’ll discuss how you can upload files with cURL.

Let’s create the curl_post_file.php file with the following contents.

When you want to upload a file, you need to create a CURLFile object in the first place. As of PHP 5.5+, it’s fairly easy to create it, as you just need to use the curl_file_create function to create a CURLFile object. The first argument of the curl_file_create function is an absolute path of the file which you want to upload.

If you are still using the older PHP version, which is not recommended, we’ve used the fallback '@' . realpath('/absolute/path/to/file/') syntax to create a file link.

Finally, we’ve set the Content-Type header to multipart/form-data as it’s going to be a multipart form POST request. Apart from that, it’s a routine cURL POST request.

So far, we’ve gone through a couple of different cURL methods that are frequently used in PHP. In the next section, we’ll see how you can use the Guzzle library, which makes things easier for you when you’re dealing with HTTP requests in PHP.

What is the Guzzle HTTP Client?

As per the official documentation:

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

Let’s quickly go through the benefits of using Guzzle over the cURL PHP functions.

  • a simple interface for different types of data
  • supports both synchronous and asynchronous requests
  • supports cURL, sockets and PHP streams
  • PSR-7 compliant
  • and more

All in all, it’s one of the best libraries to use when you want to make HTTP calls with different methods. In this section, we’ll discuss how to install Guzzle followed up by a couple of quick examples to demonstrate the power of this library!

How to Install the Guzzle Library

The official documentation recommends that you should use Composer to install Guzzle. Let’s run the following command to install Guzzle in your project.

Once it’s installed, you need to require Composer’s autoloader as shown in the following snippet.

And with that, you’re ready to use Guzzle!

How to Make a GET Request with Guzzle

In this section, we’ll see how you can send GET requests with Guzzle.

We’ll revise the example which we discussed earlier, as it will help you to understand how you could convert your existing cURL PHP code to Guzzle-based implementation.

Let’s have a look at the revised example.

Isn’t it straightforward? We’ve created an instance of the GuzzleHttpClient class, and it’s assigned to the $client variable. And now, you have access to the plenty of utility methods provided by the GuzzleHttpClient class.

In our case, we need to fetch content with the GET method, so we’ve used the get method of the GuzzleHttpClient class, and it will return the GuzzleHttpPsr7Response object. The GuzzleHttpPsr7Response object provides various methods like getStatusCode, getBody, getReasonPhrase and more. We’ve used the getBody method to fetch the response body contents.

So that’s how you can perform HTTP GET requests with Guzzle.

How to Make a POST Request with Guzzle

In this section, we’ll see how you can perform HTTP POST requests with Guzzle.

We’ll revise the curl_post_example.php example, which we discussed in the earlier section. The revised code with Guzzle looks like this.

Since this is a POST request, we need to pass the $options array as the second argument of the post method. In our example, it contains the form data that we need to submit as a POST data.

If you’re wondering how to post JSON data, you just need to change the form_params key to json, and the data will be sent as JSON!

Also, if you want to send any HTTP headers along with a request, you can do it with the headers key as shown in the following snippet.

In fact, the Guzzle library provides a lot of configuration options for every method. Also, there are multiple ways to do the same thing, so I encourage you to explore it in detail, and I’m sure it will be fun!

So that was a quick introduction of the Guzzle library along with the PHP cURL functions.

Conclusion<

Today, we explored the basics of the cURL extension in PHP. We discussed how you can perform different types of HTTP requests with cURL in PHP. Also, we went through a quick introduction of the Guzzle library, which makes life easier for developers while dealing with HTTP requests in PHP.

Leave a comment

Your email address will not be published.