如果与远程服务器没有连接,如何放弃 file_get_contents() 请求



我的运输公司有一个"API",指示我使用file_get_contents()来接收运输报价。

$zipcode=1234;
$volume=2;
$shipping_quote=file_get_contents(http://www.shipping.com?z=$zipcode&v=$volume);

有时,他们的服务器会关闭,我不会收到任何响应。有没有办法检查file_get_contents是否建立了连接?我收到"无法打开流错误"。而不是这些,我希望能够向我的用户呈现一个有意义的响应"服务器繁忙,重试"。

像这样尝试

 //initialize curl
$URL = "http://www.shipping.com";
$curlInit = curl_init($URL);
curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($curlInit,CURLOPT_HEADER,true);
curl_setopt($curlInit,CURLOPT_NOBODY,true);
curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);
//check for response
$response = curl_exec($curlInit);
curl_close($curlInit);
if ($response) 
{
    $shipping_quote=file_get_contents("http://www.shipping.com?z=$zipcode&v=$volume");
}else
{
    $shipping_quote="";
}

最新更新