PHP: Get fopen() HTTP response error code

时光总嘲笑我的痴心妄想 提交于 2019-12-11 17:49:58

问题


I would like to get the HTTP error code while opening a remote file via fopen() function.

I have the following code:

$remote = fopen ($url, "rb");

If the URL is fine, the file would be opened. Otherwise, fopen triggers an error message similar to Warning: fopen(url): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found.

I know that adding a @ before the fopen() would suppress the error message,
but how can I get the http error code instead?

Here, I want to get HTTP/1.1 404 Not Found in a variable.

Thanks.


回答1:


The $http_response_header will return the response header.
So you can get the first line by using $http_response_header[0] which in this case, will be exactly HTTP/1.1 404 Not Found.

$remote = @fopen ($url, "rb");
if (!$remote) {
   echo "Error: " . $http_response_header[0];
}


来源:https://stackoverflow.com/questions/24689153/php-get-fopen-http-response-error-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!