Sending multiple non-blocking cURL requests with PHP.

In this tutorial, I will show you how to send multiple non-blocking / asynchronous cURL requests using PHP. Furthermore, I will also show you how to get the output and HTTP response code for each request.

curl_multi_init.

They key to all of this is a PHP function called curl_multi_init. The curl_multi_init function allows us to initialize a cURL multi handle and send asynchronous HTTP requests.

Essentially, we create a big “multi handle” that consists of multiple smaller handles. You can think of the “multi handle” as a machine that stores and executes multiple requests.

Let’s take a look at the following code:

In the code above, we:

  1. Created an array of URLs that we want to send a HTTP request to.
  2. Setup an array called $requests. This array will be used to store response content, etc, so that we can access it later.
  3. Looped through each URL in the $url array and configured each request before adding it to our multi handle.
  4. Executed the multi handle using the curl_multi_exec function. Note that this function will set the variable $stillRunning to a boolean FALSE value once it has finished.
  5. Looped through each executed request and compiled the response content and HTTP status code into our $requests array for future use.
  6. We closed the multi cURL handle.
  7. We var_dumped out the $requests array.

If you run the above code, you should get a good idea of how this piece of code works. You should also notice how much faster a multi handle cURL request is than sending off multiple individual requests.

Note that you may have to change some of the options that we set in the first loop to match your own requirements.

At the end, you should be left with an array that contains the URL, the response content and the HTTP status code for each request that you executed.

Hopefully, this helped!

Facebook Comments