sami sami - 10 months ago 50
PHP Question

file_get_contents when url doesn't exist

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


If the URL is not real, it return this error message. How can I get it to error gracefully so that I know that the page doesn't exist and act accordingly without displaying this error message?

failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found
in myphppage.php on line 3

for example in zend you can say:
if ($request->isSuccessful())

$client = New Zend_Http_Client();

$request = $client->request();

if ($request->isSuccessful()) {
//do stuff with the result

ynh ynh

You need to check the HTTP response code:

function get_http_response_code($url) {
    $headers = get_headers($url);
    return substr($headers[0], 9, 3);
if(get_http_response_code('') != "200"){
    echo "error";