我有一个邮政编码查询服务,我担心任何可能的超时或服务器关闭.
如果我在初始请求的20-25之后没有得到任何HTTP响应,我会想要用JSON来响应,表示它失败了:
({ success:0 })
Run Code Online (Sandbox Code Playgroud)
您也可以file_get_contents()使用stream_context_create()设置超时(以及许多其他选项).请参阅此处以获取选项列表.
手册中的修改示例:
<?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);
?>
Run Code Online (Sandbox Code Playgroud)
如果这对你有用,我看不到任何反对使用cURL的话.