Tags
Asked 2 years ago
9 Jun 2021
Views 232
david

david posted

how to Access multiple URL at once in Curl PHP ?

how to Access multiple URL at once in Curl PHP ?
sachin

sachin
answered Apr 26 '23 00:00

In PHP cURL, you can access multiple URLs at once using the curl_multi_ * functions. These functions allow you to send multiple cURL requests in parallel and process their responses asynchronously.

Here's an example of how you can use the curl_multi_ * functions to access multiple URLs at once:



$urls = array(
    'http://example.com/api1',
    'http://example.com/api2',
    'http://example.com/api3'
);

$curl_handles = array();

// create cURL handles for each URL
foreach ($urls as $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $curl_handles[] = $ch;
}

// create a multi-handle to execute multiple requests in parallel
$multi_handle = curl_multi_init();

// add the cURL handles to the multi-handle
foreach ($curl_handles as $ch) {
    curl_multi_add_handle($multi_handle, $ch);
}

// execute the requests in parallel
$running = null;
do {
    curl_multi_exec($multi_handle, $running);
} while ($running > 0);

// process the responses
foreach ($curl_handles as $ch) {
    $response = curl_multi_getcontent($ch);
    // process the response for each URL
    echo $response;
    curl_multi_remove_handle($multi_handle, $ch);
    curl_close($ch);
}

// close the multi-handle
curl_multi_close($multi_handle);

In this example, an array of URLs is defined and cURL handles are created for each URL using a loop. These handles are added to a multi-handle using the curl_multi_add_handle () function. The curl_multi_exec () function is then called to execute the requests in parallel.

Once all the requests have been sent and their responses have been received, the curl_multi_getcontent () function is used to get the response for each request. The response can then be processed for each URL as needed.

Finally, the handles are removed from the multi-handle using the curl_multi_remove_handle() function, and the cURL handles are closed using the curl_close () function. The multi-handle is closed using the curl_multi_close () function.
Post Answer