Thursday, March 25, 2010

PHP: file_get_contents catch exception

Script has been modified and provides a neat example, look here: file_get_contents() exception handling improved

Many PHP users are looking for a way to catch the exception from file_get_contents() function. I've had my share of trying to catch one too but the amount of code required to do so is above my level. After countless hours of wasted time I decided to simply ignore the error, like this:

$a = @file_get_contents($url);

@ - simply ignores the error if there is one. Nothing will happen, no output will come up.

Recently, I had to use file_get_contents() function once again while appying object-oriented programming and a thought came to my head. I went to php.net website and checked how file_get_contents() works, again.

This is what PHP manual says:

" file_get_contents() - returns a file in a string." (We all know that)
" On failure, file_get_contents() will return FALSE. " - there is the answer.

If the function returns false, that means something went wrong and the result is not what you expected, so the simplest way to check if the function returned anything or not without handling/catching the exception would be to test the function in the IF statement, like this:

if ( file_get_contents( $url ) != false ) {
$a = file_get_contents($url);
.... whatever it is that you wanted to do with the $a string
}

Technically you are running the function twice, but this will ensure it works or not without having to go about catching exceptions.