Featured image of post Making Concurrent Requests in PHP

Making Concurrent Requests in PHP

Try out pseudo-concurrent request functionality in PHP

PHP has always operated with a page-level lifecycle, where variables from previous requests aren’t shared with subsequent ones (unlike resident memory languages).


  • Most PHP code executes sequentially from top to bottom without callback capabilities
  • The curl_multi_* function family enables “multi-threaded”-like behavior in PHP
  • Recommended library for easier implementation: https://github.com/php-curl-class/php-curl-class

Official concurrent request demo

<?php
require __DIR__ . '/../vendor/autoload.php';

use Curl\MultiCurl;

$urls = array(
    'tag3' => 'https://httpbin.org/post',
    'tag4' => 'https://httpbin.org/get',
    'tag5' => 'https://httpbin.org/html',
);

$multi_curl = new MultiCurl();

$data = [];

$multi_curl->success(function ($instance) {
    echo 'Call to ' . $instance->id . ' with "' . $instance->myTag . '" succeeded.' . "\n";
});
$multi_curl->error(function ($instance) {
    echo 'Call to ' . $instance->id . ' with "' . $instance->myTag . '" failed.' . "\n";
});
$multi_curl->complete(function ($instance) use (&$data) {
    echo 'Call to ' . $instance->id . ' with "' . $instance->myTag . '" completed.' . "\n";
    $data[] = $instance->tag;
});

foreach ($urls as $tag => $url) {
    $instance = $multi_curl->addGet($url);
    $instance->myTag = $tag;
}

// Wait for all requests to complete
$multi_curl->start();

// Tag order isn't guaranteed, depends on HTTP response speed
var_dump($data);