file_get_contents when url doesn't exist

前端 未结 8 2239
刺人心
刺人心 2020-12-01 02:37

I\'m using file_get_contents() to access a URL.

file_get_contents(\'http://somenotrealurl.com/notrealpage\');

If the URL is not real, it r

8条回答
  •  無奈伤痛
    2020-12-01 03:15

    Each time you call file_get_contents with an http wrapper, a variable in local scope is created: $http_response_header

    This variable contains all HTTP headers. This method is better over get_headers() function since only one request is executed.

    Note: 2 different requests can end differently. For example, get_headers() will return 503 and file_get_contents() would return 200. And you would get proper output but would not use it due to 503 error in get_headers() call.

    function getUrl($url) {
        $content = file_get_contents($url);
        // you can add some code to extract/parse response number from first header. 
        // For example from "HTTP/1.1 200 OK" string.
        return array(
                'headers' => $http_response_header,
                'content' => $content
            );
    }
    
    // Handle 40x and 50x errors
    $response = getUrl("http://example.com/secret-message");
    if ($response['content'] === FALSE)
        echo $response['headers'][0];   // HTTP/1.1 401 Unauthorized
    else
        echo $response['content'];
    

    This aproach also alows you to have track of few request headers stored in different variables since if you use file_get_contents() $http_response_header is overwritten in local scope.

提交回复
热议问题