我有一個郵政編碼查詢服務,我擔心任何可能的超時或服務器關閉。我應該使用file_get_contents還是curl來處理Web服務請求?
如果我沒有得到初始請求的20-25s之後的任何HTTP響應我會想用JSON標誌着迴應失敗:
({ success:0 })
我有一個郵政編碼查詢服務,我擔心任何可能的超時或服務器關閉。我應該使用file_get_contents還是curl來處理Web服務請求?
如果我沒有得到初始請求的20-25s之後的任何HTTP響應我會想用JSON標誌着迴應失敗:
({ success:0 })
您可以設置超時時間(和很多其他選項)以及stream_context_create()。有關選項列表,請參閱here。從手動
修改例如:
<?php
$opts = array(
'http'=>array(
'timeout' => 25,
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
/* Sends an http request to www.example.com
with additional headers shown above */
$contents = file_get_contents("http://example.com", false, $context);
?>
如果你是這樣的,我什麼也看不到反對使用捲曲在這個講話。
cURL有更多的功能,它可能會在你的情況下更有用。
您可以使用此
curl_setopt($ch, CURLOPT_TIMEOUT, 40); //enter the number of seconds you want to wait
你的標題和你的問題的文本提出了兩個不同的問題。 cURL和file_get_contents都可以使用具有特定返回值的超時。
如果使用cURL,則可以使用curl_setopt($ch, CURLOPT_TIMEOUT, 25) //for 25s
來設置超時。
要設置file_get_contents的超時時間,您必須將其包含在您的context中。
$opts = array(
'http'=>array(
'method'=>"GET",
'timeout'=>"25",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
然而要注意的file_get_contents,不像捲曲,有一個默認的超時時間(在選項default_socket_timeout找到)。
傳輸失敗時cURL和file_get_contents均返回FALSE
,因此捕獲失敗很容易。
+1爲例 – 2010-03-19 16:35:09