How to make asynchronous requests in php with example

By | December 25, 2019

As we know php serves requests synchronously, means each line of code executes in the synchronous manner of a script after getting the result from one line it moves to execute next line or wait for the result before jumping to execution of next  line of code.

There is a scenario where we need to make requests to some urls and they are not dependent to each other, in this case we do not want to wait for the result from one request to execute other requests. So in this case we make asynchronous request.

So here in this article i am going to explain how to make asynchronous requests in php with example.

In  this example i am using Guzzle http package . And with this package it would be very easy .

So first you will need to download Guzzle php package. You can install it through composer

php composer.phar require guzzlehttp/guzzle:~6.0

or 

composer require guzzlehttp/guzzle:~6.0

or you can directly download through the link https://github.com/guzzle/guzzle

then after you will need to include autoload file in the script to load all the classes and methods available in the script like the script below –

<?php

require_once(__DIR__ . '/vendor/autoload.php');
$client = new GuzzleHttp\Client();

$promises = [
    $client->getAsync('http://localhost')->then(function ($response) { echo '1'; }),
    $client->getAsync('https://stackoverflow.com')->then(function ($response) { echo '2'; }),
    $client->getAsync('http://www.google.com')->then(function ($response) { echo '3'; }),
    $client->getAsync('http://localhost')->then(function ($response) { echo '4'; }),
    $client->getAsync('http://localhost')->then(function ($response) { echo '5'; }),
    $client->getAsync('https://www.phpclasses.org')->then(function ($response) { echo '6'; }),
    $client->getAsync('http://localhost')->then(function ($response) { echo '7'; }),
    $client->getAsync('http://localhost')->then(function ($response) { echo '8'; }),
    $client->getAsync('http://localhost')->then(function ($response) { echo '9'; }),
];

$results = GuzzleHttp\Promise\unwrap($promises);

// Wait for the requests to complete, even if some of them fail
$results = GuzzleHttp\Promise\settle($promises)->wait();

print "finished." . PHP_EOL;

In the above example i have included autoload file then created guzzle http client object that is stored in $client variable and for each  http request i used getAsync method with the url.

The request which will get response first will echo the number. it would not be matter in which order the request has made.

It is really a very simple method to make asynchronous calls in php. You can try this in your project, it you have any issue with this code, you can comment in the comment box, i will definitely try to solve your problem.

Hope you will love the script!