tags:

views:

52

answers:

3

Why doesn't the following print "Error!" but only prints the 'failed to open stream...' warning?

try {
    file_get_contents('www.invalid-url.com');
} catch (Exception $e) {
    echo 'Error!';
}
+2  A: 

It returns FALSE on error, it doesn't throw and exception.

So you could use @ to suppress the warning (if required) and check the result to see if there was an error

$content = @file_get_contents('http://www.example.com');
if ( $content === FALSE ){
    echo "Error!";
}
Yacoby
+3  A: 

file_get_contents doesn't throw an exception, but returns FALSE if it fails. file_get_contents is a highly primitive function. If you want more advanced feedback, use cURL.

E.g. something like this:

$curl = curl_init('your URL here');

// Return the output to a string instead of the screen with CURLOPT_RETURNTRANSFER
curl_setopt($pCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($pCurl, CURLOPT_TIMEOUT, 10);

$content = curl_exec($curl);
$info = curl_getinfo($curl);

if($info['http_code'] === 200)
{
    return $content;
}
TheGrandWazoo
that explains alot:)
breez
A: 

PHP doesn't use exceptions by default but an error message mechanism. If you want exceptions you could use a custom error handler like in http://php.net/manual/en/class.errorexception.php

The more PHP'ish way would be to shutdown the error message and check the return code. Shutting down can be done globally by error_reporting(0); or ini_set('display_errors', false); or using the @ operator.

<?php
if (!@file_get_contents(....)) {
    echo "ERROR";
}
?>
johannes
Suspressing error messages never helped anyone life getting better. This isn't the way to go. If you reach a point where you must debug this code you will slap yourself against your head when you realize you've been throwing away valid debug information.
TheGrandWazoo
Globally suppressing errors is a very bad idea, but suppressing errors with `@` on an individual statement here and there may sometimes be the simplest solution -- even then, be aware that even supressed errors are inefficient: the error handler is always, called, even when an error is suppressed. Suppressing errors on anything that results in more than one line of PHP being executed (like an `include` or a call to a user-defined function), on the other hand, is definitely a good way to make debugging hell.
Frank Farmer
so the best idea would be to leave error reporting on while developing an turning them of globally when the code is production ready?
breez
Frank, I consider it the best practice to disable display_Errors on the production system and log all errors. The @ makes debugging very hard ...
johannes