<?php
/* 1. URLs a consultar */
$urls = [
'https://httpbin.org/delay/2',
'https://httpbin.org/uuid',
'https://httpbin.org/headers'
];
/* 2. Crear el “multi handle” */
$mh = curl_multi_init();
/* 3. Crear un handle individual para cada URL y añadirlo al multi */
$handles = [];
foreach ($urls as $i => $url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['Accept: application/json']
]);
curl_multi_add_handle($mh, $ch);
$handles[$i] = $ch; // guardamos referencia para después
}
/* 4. Ejecutar todas las transferencias en paralelo */
$running = 0;
do {
curl_multi_exec($mh, $running);
if ($running) {
// esperar activamente hasta que haya actividad (evita busy-wait)
curl_multi_select($mh);
}
} while ($running > 0);
/* 5. Recoger respuestas y cerrar */
$responses = [];
foreach ($handles as $i => $ch) {
if (curl_errno($ch) === 0) {
$responses[$i] = [
'url' => $urls[$i],
'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
'body' => curl_multi_getcontent($ch)
];
} else {
$responses[$i] = [
'url' => $urls[$i],
'error' => curl_error($ch)
];
}
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
curl_multi_close($mh);
/* 6. Ya tienes las tres respuestas, puedes devolverlas al cliente */
header('Content-Type: application/json');
echo json_encode($responses, JSON_PRETTY_PRINT);
/* ó */
$> composer require guzzlehttp/guzzle:^7.0
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
$client = new Client(['timeout' => 10]);
$promises = [
$client->getAsync('https://httpbin.org/delay/2'),
$client->getAsync('https://httpbin.org/uuid'),
$client->getAsync('https://httpbin.org/headers')
];
$responses = Promise\Utils::settle($promises)->wait(); // espera a todas
foreach ($responses as $r) {
echo $r['value']->getBody();
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter