Why does phpcurl support concurrent requests with millisecond control timeout? To ensure the performance and stability of the service calls of the current interface, we will control the concurrency and timeout of the called third-party interface. Code implementation (available on the Internet) publicstaticfunctioncurlMultiRequest ($ urls, $ optionsarray () {$ charra php curl supports concurrent requests and controls timeout in milliseconds
Why?
To ensure the performance and stability of the service calls of the current interface, we will control the concurrency and timeout of the called third-party interface.
Code implementation (available online)
public static function curlMultiRequest($urls, $options = array()) { $ch= array(); $results = array(); $mh = curl_multi_init(); foreach($urls as $key => $val) { $ch[$key] = curl_init(); if ($options) { curl_setopt_array($ch[$key], $options); } curl_setopt($ch[$key], CURLOPT_URL, $val); curl_multi_add_handle($mh, $ch[$key]); } $running = null; do { curl_multi_exec($mh, $running); } while ($running > 0); // Get content and remove handles. foreach ($ch as $key => $val) { $results[$key] = curl_multi_getcontent($val); curl_multi_remove_handle($mh, $val); } curl_multi_close($mh); return $results; }
Call method:
$ Urls = ['http: // www.baidu.com ', 'http: // www.qq.com']; $ opts = [CURLOPT_HEADER => false, CURLOPT_TIMEOUT_MS => 50, // execution script timeout // CURLOPT_CONNECTTIMEOUT_MS => 50, // Network site selection timeout CURLOPT_RETURNTRANSFER => true, CURLOPT_NOSIGNAL => true, // this parameter must be set in milliseconds]; curlMultiRequest ($ urls, $ opts );
Notes
1. added to cURL 7.16.2 in milliseconds. Available from PHP 5.2.3
2. when CURLOPT_TIMEOUT_MS, CURLOPT_CONNECTTIMEOUT_MS is not defined
if (!defined('CURLOPT_CONNECTTIMEOUT_MS')) { define('CURLOPT_CONNECTTIMEOUT_MS', 156);}if (!defined('CURLOPT_TIMEOUT_MS')) { define('CURLOPT_TIMEOUT_MS', 155);}
References:
- Http://stackoverflow.com/questions/9062798/php-curl-timeout-is-not-working
- Http://www.laruence.com/2014/01/21/2939.html