如果您正在使用的HTTP URL的工作只有你能做到以下幾點:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1
)
));
for ($i = 0; $i <=59; $i++) {
file_get_contents("http://example.com/", 0, $ctx);
}
然而,這僅僅是讀超時,這意味着之間有兩個讀操作時(或第一次讀取操作之前的時間)。如果下載速度不變,下載速度不應該有這樣的差距,下載可能需要一個小時。
如果你想整個下載用不了一秒鐘,你不能使用file_get_contents()
了更多。在這種情況下,我鼓勵使用curl
。像這樣:
// create curl resource
$ch = curl_init();
for($i=0; $i<59; $i++) {
// set url
curl_setopt($ch, CURLOPT_URL, "example.com");
// set timeout
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
}
使用流上下文將超時設置爲1秒。請參閱http://stackoverflow.com/questions/10236166/does-file-get-contents-have-a-timeout-setting –