项目中经常需要访问各种外部资源,因各种因素造成请求地址可能出现无法正常访问的情况。此时,如果程序没有做容错处理,可能会出现异常情况。
利用获取远程资源的header头信息中的响应状态是否为200可以判断外部资源是否可以访问。
/**
* 校验网络地址是否有效
* @param string $url url地址
* @return bool
*/
public static function isValidNetworkUrl($url)
{
$returnResult = false;
$headerInfo = get_headers($url);
if (is_array($headerInfo) && !empty($headerInfo) && isset($headerInfo[0]) && !empty($headerInfo[0]))
{
$returnStatus = $headerInfo[0];
if(strpos($returnStatus,'200') !== false)
{
$returnResult = true;
}
unset($returnStatus);
}
unset($headerInfo);
return $returnResult;
}