Created
January 18, 2021 10:58
-
-
Save nhuhoai/4b7982a4df65c6264ed4c69f064798f3 to your computer and use it in GitHub Desktop.
Multi curl example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Multi curl example | |
* | |
* PHP Version 7.4 | |
* | |
* @category Example | |
* @package MultiCurl | |
* @author Nhu-Hoai Robert Vo <[email protected]> | |
* @copyright 2021 Nhu-Hoai Robert Vo | |
* @license https://spdx.org/licenses/MIT.html MIT License | |
* @version GIT: 0.1.0 | |
* @link https://www.nhuvo.ch/ | |
* @since 0.1.0 | |
*/ | |
/// Set timeout to 2 seconds | |
$timeout = 2; | |
/// Requests | |
$requests = []; | |
// First request | |
$requests[0] = curl_init(); | |
curl_setopt_array( | |
$requests[0], | |
[ | |
CURLOPT_URL => "https://www.github.com/", | |
CURLOPT_TIMEOUT => $timeout, | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_RETURNTRANSFER => true | |
] | |
); | |
// Second request | |
$requests[1] = curl_init(); | |
curl_setopt_array( | |
$requests[1], | |
[ | |
CURLOPT_URL => "https://www.google.com/", | |
CURLOPT_TIMEOUT => $timeout, | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_RETURNTRANSFER => true | |
] | |
); | |
// Third request | |
$requests[2] = curl_init(); | |
curl_setopt_array( | |
$requests[2], | |
[ | |
CURLOPT_URL => "https://www.nhuvo.ch/", | |
CURLOPT_TIMEOUT => $timeout, | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_RETURNTRANSFER => true | |
] | |
); | |
// Fourth request | |
$requests[3] = curl_init(); | |
curl_setopt_array( | |
$requests[3], | |
[ | |
CURLOPT_URL => "https://fake.address.does.surely.not.exist.com", | |
CURLOPT_TIMEOUT => $timeout, | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_RETURNTRANSFER => true | |
] | |
); | |
/// Init multi curl | |
$mh = curl_multi_init(); | |
// Handle all requests into multi curl | |
foreach ($requests as $request) { | |
curl_multi_add_handle($mh, $request); | |
} | |
// Waiting until every request has been done | |
do { | |
$status = curl_multi_exec($mh, $active); | |
if ($active) { | |
curl_multi_select($mh); | |
} | |
} while ($active && $status == CURLM_OK); | |
// Show status | |
$count = 1; | |
$br = "<br />"; | |
if (php_sapi_name() == "cli") { | |
$br = "\n"; | |
} | |
while (($request = curl_multi_info_read($mh)) !== false) { | |
print "Request #" . $count . $br; | |
print "URL: " . curl_getinfo($request["handle"])["url"] . $br; | |
print "Duration: " . curl_getinfo($request["handle"])["total_time"] . "ms" . $br; | |
print "Curl error: " . curl_errno($request["handle"]) . $br . $br; | |
$count++; | |
} | |
// Close multi curl handler | |
curl_multi_close($mh); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment