2014-05-13 23 views
1

我不能讓file_get_contents的工作時間超過1秒,如果這是不可能的 - 我需要跳到下一個循環。我可以在PHP上爲()添加超時嗎?

for ($i = 0; $i <=59; ++$i) { 
$f=file_get_contents('http://example.com'); 

if(timeout<1 sec) - do something and loop next; 
else skip file_get_contents(), do semething else, and loop next; 
} 

是否有可能做出這樣的功能?

其實我使用curl_multi,我不能fugure如何設置超時在整個curl_multi請求。

+0

使用流上下文將超時設置爲1秒。請參閱http://stackoverflow.com/questions/10236166/does-file-get-contents-have-a-timeout-setting –

回答

1
$ctx = stream_context_create(array(
    'http' => array(
     'timeout' => 1 
     ) 
    ) 
); 
file_get_contents("http://example.com/", 0, $ctx); 

Source

2

如果您正在使用的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

爲什麼在for循環中一次又一次地定義上下文?它可以不在外面定義一次並在for循環中使用嗎? – Latheesan

+0

是的,當然 – hek2mgl

+0

@ hek2mgl我實際上使用curl_setopt($ curly [$ id],CURLOPT_TIMEOUT,1);對於具有5個不同url請求的curl_multi。但它可以加起來5秒。我如何爲整個curl_multi請求設置1秒超時? – user1482261

相關問題