我个人建议您使用 cURL 而不是 file_get_contents。 file_get_contents 非常适合面向基本内容的 GET 请求。但标头、HTTP 请求方法、超时、重定向和其他重要的事情对它来说并不重要。
不过,要检测状态代码(403、200、500 等),您可以使用获取标题()致电或$http_response_header自动分配的变量。
$http_response_header是一个预定义的变量,并且它会在每次更新时更新文件获取内容 call.
以下代码可能会直接为您提供状态代码(403、200 等)。
preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#", $http_response_header[0], $match);
$statusCode = intval($match[1]);
更多信息和变量内容请查看官方文档
$http_response_header — HTTP 响应标头 http://php.net/manual/en/reserved.variables.httpresponseheader.php
get_headers — 获取服务器响应 HTTP 请求而发送的所有标头 http://php.net/manual/en/function.get-headers.php
(更好的选择)cURL http://php.net/manual/en/book.curl.php
警告关于$http_response_header,(来自 php.net) http://php.net/manual/en/reserved.variables.httpresponseheader.php#113361
请注意,HTTP 包装器有一个硬
标题行的字符数限制为 1024 个。收到的任何长度超过此值的 HTTP 标头都将被忽略,并且不会出现在 $http_response_header 中。 cURL 扩展没有这个限制。