2014-12-06 60 views
1

我有一個網站,我需要確定用戶的位置,所以我使用webservice,它爲我提供了有關我的用戶(使用他的IP地址)的詳細信息。檢查file_get_contents網址是否正常工作

我的功能看起來是這樣的:

$user_ip = $_SERVER['REMOTE_ADDR']; 
$json_url = 'http://example.com/'.$user_ip; 
$json = file_get_contents($json_url); 
$obj = json_decode($json); 

今天早上這個Web服務有問題(500錯誤,過多的連接,壞網關...)和我的網站被加載很長的時間。

所以我有一個問題:是否有可能爲file_get_contens函數設置超時?或者也許有辦法讓服務器不能正常工作?

+0

我認爲你應該使用捲曲,而不是file_get_contents()函數 – Khushboo 2014-12-06 12:52:47

回答

1

您可以設置timeout選項http上下文:

$opts = array('http' => 
    array(
     'timeout' => 5 
    ) 
); 

$result = file_get_contents($url, false, stream_context_create($opts)); 

檢查的文檔:


另一種方法是通過ini_set()設置默認套接字超時:

$st = ini_get("default_socket_timeout"); // backup current value 
ini_set("default_socket_timeout", 5000); // 5 seconds 

$content = file_get_contents($url); 
if($content === false) { 
    // error handling 
} 

ini_set("default_socket_timeout", $st); // restore previous value