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!'; } 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; } 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"; } ?> @ 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.