PHP: Get fopen() HTTP response error code

2019-09-18 06:01发布

问题:

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];
}