简体   繁体   中英

PHP: Get fopen() HTTP response error code

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 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM