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
How to make asynchronous HTTP requests in PHP ?
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.
4 min read
How to make a redirect in PHP?
Redirection from one page to another in PHP is commonly achieved using the following two ways:Using Header Function in PHP: The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer Protocol) header to the client. Syntax: header( $header, $replace, $
2 min read
How to read any request header in PHP
HTTP Header: HTTP headers are the code that transfers the data between web server and browser. The HTTP headers are mainly intended for the communication between the server and the client in both directions. HTTP Request Header: When type a URL in the address bar of browser and try to access it, the
2 min read
How to echo HTML in PHP ?
While making a web application with PHP, we often need to print or echo few results in form of HTML. We can do this task in many different ways. Some of methods are described here: Using echo or print: PHP echo or print can be used to display HTML markup, javascript, text or variables. Example 1: Th
2 min read
How to send a GET request from PHP?
There are mainly two methods to send information to the web server which are listed below: GET Method: Requests data from a specified resource. POST Method: Submits data to be processed to a specified resource. Get Method: The GET method sends the encoded user information appended to the page reques
2 min read
How to Identify Server IP Address in PHP?
What is an IP Address?IP Address or Internet Protocol Address is a numerical value assigned to every device on the network that uses the Internet Protocol for Communication. An IP address serves two major functions: Network/Host interface identificationLocation addressingStatic IP addresses that do
2 min read
How to test a URL for 404 error in PHP?
Checking if a Webpage URL exists or not is relatively easy in PHP. If the required URL does not exist, then it will return 404 error. The checking can be done with and without using cURL library. cURL: The cURL stands for âClient for URLsâ, originally with URL spelled in uppercase to make it obvious
2 min read
How to change the session timeout in PHP?
In PHP, sessions are maintained to check if the user is active. When the user becomes inactive and the user forgets to logout from the web page, there is a chance of other users viewing the page causing security breach. By default, a session in PHP gets destroyed when the browser is closed. Session
3 min read
How to check form submission in PHP ?
Given a form and the task is to check form submitted successfully or not. Use the PHP program for the backend to check form submission and HTML and CSS to create the form as frontend. Syntax: if (!empty($_POST)) if (isset($_POST['submit'])) Use these two statements to check whether the form submitte
3 min read
How to automatically start a download in PHP ?
This post deals with creating a start downloading file using PHP. The idea is to make a download button which will redirect you to another page with the PHP script that will automatically start the download. Creating a download button: <!DOCTYPE html> <html> <head> <meta name=
2 min read
How to Install php-curl in Ubuntu ?
CURL stands for Client URL. It is a Linux Terminal command which is used to transferring data from one server to another server. It is a free and open-source data transfer tool that uses the following protocols: IMAP, IMAPS, POP, POP3, POP3S, DICT, FILE HTTP, HTTPS, SMB, SMBS, SMTP, SMTPS, FTP, FTPS
2 min read
How to get the MAC and IP address of a connected client in PHP?
What is a MAC address? MAC is the abbreviation of "Media Access Control" and it is a 48-bit physical address associated with every networking device. It is printed on the NIC(Network Interface Card) and is globally unique for every networking device. MAC address is used by the data-link layer to rou
3 min read
How to check the existence of URL in PHP?
Existence of an URL can be checked by checking the status code in the response header. The status code 200 is Standard response for successful HTTP requests and status code 404 means URL doesn't exist. Used Functions: get_headers() Function: It fetches all the headers sent by the server in response
2 min read
How to select and upload multiple files with HTML and PHP, using HTTP POST?
In this article, we will look at how to upload multiple files with HTML and PHP. Multiple image upload allows the user to select multiple files at once and upload all files to the server. index.html Create a simple HTML page to select multiple files and submit it to upload files on the server. Here,
3 min read
How to post data using file_get_contents in PHP ?
The file_get_contents() function in PHP is used to read the contents of a file and make HTTP requests using GET and get HTTP responses using POST methods. The HTTP POST request can be made using the $context parameter of the file_get_contents() function, which posts the specified data to the URL spe
3 min read
How to Get Local IP Address of System using PHP ?
IP (Internet Protocol) Address is an address of your network hardware. It helps in connecting your computer to other devices on your network and all over the world. An IP Address is made up of numbers or characters combined by '.' symbol. Example: It is an example of IP address. 506.457.14.512 All d
3 min read
How to call PHP Function on the Click of a Button?
Given a document containing HTML and PHP code and the task is to call the PHP function after clicking on the button. Â Calling a PHP function using the HTML buttonCreate an HTML form document that contains the HTML button. When the button is clicked the method POST is called. The POST method describ
2 min read
How to open a PDF files in web browser using PHP?
Opening a PDF file in a web browser using PHP involves serving the PDF directly to the clientâs browser. This is achieved by setting the appropriate HTTP headers (Content-Type and Content-Disposition) in PHP, which instructs the browser to display the PDF instead of downloading it. Note: PHP doesn't
2 min read
How to get return text from PHP file with ajax ?
In this article, we will see how to get return the text from the PHP file with ajax. Ajax is an acronym for Asynchronous JavaScript and XML is a series of web development techniques that build asynchronous web applications using many web technologies on the client-side. Without reloading the web pag
2 min read