Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid file_get_contents error: "Couldn't resolve host name"

Tags:

php

I succesfully fetch websites with

file_get_contents("http://www.site.com");

However, if the url doesn't exist, or not reachable, I am getting

Warning: file_get_contents(http://www.site.com) [function.file-get-contents]: 
failed to open stream: operation failed in /home/track/public_html/site.php 
on line 773

Is it possible to echo "Site not reachable"; instead of the error ?

like image 993
user198989 Avatar asked May 25 '13 13:05

user198989


2 Answers

You can use the silence operator @ together with $php_errormsg:

if(@file_get_contents($url) === FALSE) {
    die($php_errormsg);
}

Where the @ suppresses the error message, the message text will be available for output in $php_errormsg

But note that $php_errormsg is disabled by default. You'll have to turn on track_errors. So add at the top of your code:

ini_set('track_errors', 1);

However there is a way that does not depend on track errors:

if(@file_get_contents($url) === FALSE) {
    $error = error_get_last();
    if(!$error) {
        die('An unknown error has occured');
    } else {
        die($error['message']);
    }
}
like image 143
hek2mgl Avatar answered Sep 18 '22 07:09

hek2mgl


I would perfer to trigger exceptions instead of error messages:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    // see http://php.net/manual/en/class.errorexception.php
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}

set_error_handler("exception_error_handler");

Now you can catch the error like this:

try {
    $content = file_get_contents($url);
} catch (ErrorException $ex) {
    echo 'Site not reachable (' . $ex->getMessage() . ')';
}
like image 26
sroes Avatar answered Sep 18 '22 07:09

sroes