Friday, October 22, 2010

PHP: file_get_contents() exception handling improved (example)

Here is a straight up example on how to effectively call the function file_get_contents() and properly handle its errors with exception handling.

If you're not familiar with exception handling here is the basic run down.

1. We set the link into $url variable which we want to parse.

2. Using try{} block we test our code for errors.

3. Our variable $page_contents has a symbol '@' in front of it, this symbol ignores any errors raised by that piece of code on that line only.

4. Since function file_get_contents() returns only FALSE when it fails we check our variable $page_contents if it equals to FALSE or not.

5. If the variable $page_contents does in fact equal to FALSE this means function file_get_contents() has failed and we don't want to proceed further. So, the line 14 intentionally throws an error at the script with a predefined message. Unlike other programming languages where errors are caught automatically PHP requires this to be done manually.

6. Catch{} block is responsible for catching any errors thrown at it by the try{} block. Catch{} block will handle errors as it is defined, in our case it's just printing the error message.

Exception class itself is quite big and you can modify it to catch different types of errors so dig in and explore.

Post some feedback if you got it working. Enjoy!


  1. Not working. Don't know why..

  2. Make sure you're using the latest version of PHP where OOP is actually built-in.

  3. working great, thanx, was looking for this.