get_headers(string $url, bool $associative = false, ?resource $context = null): array|false
get_headers() 返回一个数组,包含有服务器响应一个 HTTP 请求所发送的标头。
接下来请看 DEMO
/**
* 使用header信息判断远程服务器的某个文件是否存在
* @param $url
* @param int $timeout
* @return false
*/
public static function fileExistsOnRemote($url,$timeout=5){
$headerInfos=@get_headers($url,false,stream_context_create([
'http'=>[
'timeout'=>$timeout,
'method'=>'HEAD',
]
]));
if (!$headerInfos || !isset($headerInfos[0])){
return false;
}
$regex='/HTTP\/\d(?:\.\d)?\s+(\d+)/';
if (!preg_match($regex,$headerInfos[0],$matchs)){
return false;
}
$httpCode=intval($matchs[1]);
return $httpCode>=200 && $httpCode<300;
}
使用 stream_context_create
创建一个上下文,并设置请求方式为 HEAD
,设置一个请求超时。