HTTP請求有兩個超時時間:一個是連接超時時間,另一個是數據傳輸的最大允許時間(請求資源超時時間)。
使用curl命令行
連接超時時間用 --connect-timeout 參數來指定
數據傳輸的最大允許時間用 -m 參數來指定
例如:
curl --connect-timeout 10 -m 20 "http://XXXXXXX"
連接超時的話,出錯提示形如:
curl: (28) connect() timed out!
數據傳輸的最大允許時間超時的話,出錯提示形如:
curl: (28) Operation timed out after 2000 milliseconds with 0 bytes received
使用PHP的curl_init
連接超時時間
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
數據傳輸的最大允許時間
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
使用curl_error($ch)查看錯誤的詳情
如
<?php // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); curl_setopt($ch, CURLOPT_TIMEOUT, 30); // grab URL and pass it to the browser curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); var_dump(curl_error($ch));
使用PHP的fsockopen
連接超時時間
fsockopen( $hostname, $port, $errno, $errstr, $timeout);
數據傳輸的最大允許時間
暫時不清楚,雖然可以通過stream_set_timeout和stream_get_meta_data(需放在fread之后才有效果)得到是否數據傳輸超時,但是不能在設置的超時時間內停止請求,所以目標頁內容如果sleep請求頁會一直停止直到達到最大執行時間。
示例
<?php $fp = fsockopen("www.example.com", 80); if (!$fp) { echo "Unable to open\n"; } else { fwrite($fp, "GET / HTTP/1.0\r\n\r\n"); stream_set_timeout($fp, 2); $res = fread($fp, 2000); $info = stream_get_meta_data($fp); fclose($fp); if ($info['timed_out']) { echo 'Connection timed out!'; } else { echo $res; } } ?>
使用file_get_contents
連接超時時間和數據傳輸的最大允許時間均為設置的timeout,如
<?php $timeout = 60; $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n", 'timeout' => $timeout ) ); $context = stream_context_create($options); $contents = file_get_contents($source, false, $context); ?>
file_get_contents模擬post和get
function http_request($url, $post = null) { $timeout=30; if(is_array($post)) { ksort($post); $options['http'] = array ( 'timeout'=>$timeout, 'method' => 'POST', 'content' => http_build_query($post, '', '&'), ); } $context = stream_context_create($options); return file_get_contents($url, false, $context); }