相关文章推荐
好帅的小马驹  ·  Error running ...·  5 月前    · 
爱健身的跑步鞋  ·  java - ...·  1 年前    · 
坚韧的凉面  ·  請問logrotate ...·  1 年前    · 

CURLOPT_TIMEOUT 设置cURL允许执行的最长秒数
CURLOPT_TIMEOUT_MS 设置cURL允许执行的最长毫秒数
CURLOPT_CONNECTTIMEOUT 在发起连接前等待的时间,如果设置为0,则无限等待
CURLOPT_CONNECTTIMEOUT_MS 尝试连接等待的时间,以毫秒为单位。如果设置为0,则无限等待

CURLOPT_TIMEOUT_MS 在cURL 7.16.2中被加入。从PHP 5.2.3起可使用。
所以使用的时候请先查看libcurl版本 curl --version。

但是这个函数有个bug,如果时间小于1000毫秒也就是1秒的话,会立马报错,查看下面说明

  If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature"  on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached".  The explanation for this behavior is:
  "If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."
  What this means to PHP developers is "You can use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"
  The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.
  The solution is to disable signals using CURLOPT_NOSIGNAL.  Here's an example script that requests itself causing a 10-second delay so you can test timeouts:

增加 curl_setopt($ch, CURLOPT_NOSIGNAL, 1) 可以解决此问题:

if (!isset($_GET['foo'])) {
    // Client
    $ch = curl_init('http://localhost/timeout.php?foo=bar');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
    $data = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);
    if ($curl_errno > 0) {
         echo "cURL Error ($curl_errno): $curl_error\n";
    } else {
         echo "Data received: $data\n";
} else {
    // Server
    sleep(10);
    echo "Done.";
                    CURLOPT_TIMEOUT                     设置cURL允许执行的最长秒数CURLOPT_TIMEOUT_MS                     设置cURL允许执行的最长毫秒数CURLOPT_CONNECTTIMEOUT     在发起连接前等待的时间,如果设置为0,则无限等待CURLOPT_CONNECTTIMEOU...
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200); //限制响应时间200
				
curl介绍 curl是一个开源的网络链接库,支持http, https, ftp, gopher, telnet, dict, file, and ldap 协议。之前均益介绍了python版本的pycurlhttp://junyiseo.com/python/607.html,现在介绍怎么使用php版本的URL. curl get请求 function curl_get($url){ $header = array( 'Accept: application/json', ); $cur...