Search code examples
phpexceptionincludetry-catch

PHP catch a failed include


I'm trying to include a file, and catch it if the file does not exist / can not be opened. I would have thought that a simple try/catch statement would have worked but PHP seems to completely ignore it, and error out.

Any ideas? I know there are other questions like this on stackoverflow, I've seen them, but none of them seem to have a proper, working answer.


Solution

  • You can check the return value of include to see if it failed or not:

    if((@include $filename) === false)
    {
        // handle error
    }
    

    You'll note I included the error suppression operator (@ ) to hide the standard error messages from being displayed.