How to make asynchronous HTTP requests in PHP ?
Last Updated :
30 Sep, 2024
Asynchronous HTTP requests in PHP allow multiple requests to be sent without waiting for a response before proceeding. This enables non-blocking operations, improving performance by executing other tasks while waiting for the server's response, typically achieved using libraries like cURL or Guzzle.
To make asynchronous HTTP requests in PHP, you can use cURL's curl_multi_exec() function for handling multiple requests simultaneously, or utilize libraries like Guzzle, which provides built-in support for asynchronous requests using promises and non-blocking I/O.
Guzzle 6: Guzzle is a PHP HTTP client that helps to send HTTP requests. These methods can be used to send asynchronous HTTP requests.
- RequestAsync,
- SendAsync,
- GetAsync,
- HeadAsync,
- PutAsync,
- PostAsync,
- DeleteAsync,
- patchAsync
Download Guzzle php package.Can be installed through composer.
php composer.phar require guzzlehttp/guzzle:~6.0
or
composer require guzzlehttp/guzzle:~6.0
Please include the "autoload" file in the script part of the code so that it loads all the classes and methods.
PHP
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$client = new GuzzleHttp\Client();
$promises = [
$client->getAsync('http://localhost')
->then(function ($response)
{ echo '10'; }),
$client->getAsync('http://www.google.com')
->then(function ($response)
{ echo '20'; }),
$client->getAsync('http://localhost')
->then(function ($response)
{ echo '30'; }),
$client->getAsync('http://localhost')
->then(function ($response)
{ echo '40'; }),
$client->getAsync('http://localhost')
->then(function ($response)
{ echo '50'; }),
$client->getAsync('http://localhost')
->then(function ($response)
{ echo '60'; }),
$client->getAsync('http://localhost')
->then(function ($response)
{ echo '70'; }),
];
$results = GuzzleHttp\Promise\unwrap($promises);
// Please wait for a while to complete
// the requests(some of them may fail)
$results = GuzzleHttp\Promise\settle(
$promises)->wait();
print "finish/over." . PHP_EOL;
?>
In the above code, the "autoload" file is included, and then the Guzzle Http client object is created which is stored in the "client" variable and for each Http request getAsync() method is used with the URL. The request getting the first response will print the number. The order of the request will not matter.
Asynchronous HTTP requests using Promise: A single result of an asynchronous operation represents a Promise. Asynchronous requests are used in the non-blocking of the HTTP operations. When asynchronous HTTP requests send a promise, it gets returned.
Execute a request using HTTPlug:
$request = $messageFactory->createRequest(
'GET', 'http://php-http.org');
$promise = $client->sendAsyncRequest($request);
echo 'Non-blocking!';
Wait: The "promise" which is returned from the above, implements http\Promise\Promise. The response is not known yet during this point of time. Wait for that response to arrive.
try {
$response = $promise->wait();
} catch (\Exception $exception) {
echo $exception->getMessage();
}
Then: Instead of waiting, we can perform steps asynchronously. Call the then method with two arguments.
- One callback that will be executed if the request turns out to be successful.
- Callback that will be executed if the request results in an error.
// Success Callback
function (ResponseInterface $response) {
echo 'New response!';
// Write status code to the log file
file_put_contents('responses.log',
$response->getStatusCode() . "\n", FILE_APPEND);
return $response;
},
// Failure Callback
function (\Exception $exception) {
echo 'We have a problem';
throw $exception;
}
Concurrency in Promise: Concurrency means multiple computations taking place at the same time. It is good when we deal with a lot of request at the same time. For concurrency, we must use "EachPromise" class and yield generator and at last add wait() to the end of the program.
PHP
<?php
use GuzzleHttp\Promise\EachPromise;
use GuzzleHttp\Psr7\Response;
$users = ['one', 'two', 'three'];
$promises = (function () use ($users) {
foreach ($users as $user) {
// Using generator
yield $this->getAsync(
'https://api.demo.com/v1/users?username='
. $user);
}
})();
$eachPromise = new EachPromise($promises, [
// Number of concurrency
'concurrency' => 4,
'fulfilled' => function (Response $response) {
if ($response->getStatusCode() == 200) {
$user = json_decode(
$response->getBody(), true);
// processing response of the user
}
},
'rejected' => function ($reason) {
// handle promise rejected
}
]);
$eachPromise->promise()->wait();
?>
Building a multi-thread cURL request: Generally, we can handle multiple requests. First, we trigger the first one and process the response, then the second and third, and so on. But, this process is slow and time-consuming. But cURL offers the curl_multi_* functions to handle any async requests.
$running = null;
$mh = curl_multi_init();
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, 'https://endpoint.com');
// Other curl options....
curl_multi_add_handle($mh, $ch1);
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'https://endpoint.com');
// Other curl options....
curl_multi_add_handle($mh, $ch2);
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh);
} while ($running > 0);
$r1 = curl_multi_getcontent($ch1);
$r2 = curl_multi_getcontent($ch2);
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
The responses get collected in the "r1" and "r2" variables. With the help of these cURL functions, we can trigger requests parallel to save time and process the responses quicker.
Similar Reads
Asynchronous HTTP Requests with Python
Performing multiple HTTP requests is needed while working with applications related to data preprocessing and web development. In the case of dealing with a large number of requests, using synchronous requests cannot be so efficient because each request must wait for the previous request to get comp
4 min read
How to make HTTP requests in Node ?
In the world of REST API, making HTTP requests is the core functionality of modern technology. Many developers learn it when they land in a new environment. Various open-source libraries including NodeJS built-in HTTP and HTTPS modules can be used to make network requests from NodeJS.There are many
4 min read
How to Send an HTTP POST Request in JS?
We are going to send an API HTTP POST request in JavaScript using fetch API. The FetchAPI is a built-in method that takes in one compulsory parameter: the endpoint (API URL). While the other parameters may not be necessary when making a GET request, they are very useful for the POST HTTP request. Th
2 min read
How to make async functions in PHP ?
In this article, we'll learn about the async function in PHP. Let us understand what is the meaning of Async (Asynchronous): A program does not need to be executed line by line. The program calls the function and moves further (does not wait for the function to return). It will execute in the backgr
4 min read
Make HTTP requests in Angular?
In Angular, making HTTP requests involves communicating with a server to fetch or send data over the internet. It's like asking for information from a website or sending information to it. Angular provides a built-in module called HttpClientModule, which simplifies the process of making HTTP request
4 min read
How to Use jQueryâs ajax() Function for Asynchronous HTTP Requests ?
In this article, we are going to see how we can use jQuery's ajax() function to call backend function asynchronously or in other words HTTP Requests. AJAX is a set of web development techniques used by client-side frameworks and libraries to make asynchronous HTTP calls to the server. AJAX stands fo
4 min read
How to cancel an $http request in AngularJS ?
In AngularJS, we use different sources to fetch the data as per our needs. We call different data source APIs using $http requests. We can fetch the data along with cancelling the real-time running request. In AngularJS, we can use the $q service along with the promises to cancel the request. Also,
4 min read
How to send HTTP response code in PHP?
HTTP Response code: There are three approaches to accomplish the above requirement, depending on the version. For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-cas
2 min read
What is an asynchronous request in AJAX ?
In this article, we will have a deep look into Asynchronous AJAX requests. Basically, AJAX provides two types of requests namely Synchronous AJAX and Asynchronous AJAX. Asynchronous requests in AJAX don't wait for a response from the server whereas synchronous waits for the response. When asynchrono
3 min read
How to make a request using HTTP basic authentication with PHP curl?
Making secure API requests is a common requirement in web development, and PHP provides a powerful tool for this purpose, which is cURL. The challenge is to seamlessly integrate HTTP basic authentication with PHP cURL for secure API communication. This involves not only transmitting sensitive user c
3 min read