12

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.

3 Answers 3

32

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.

Sign up to request clarification or add additional context in comments.

3 Comments

using @ is a very dirty solution
I think using @, the error control operator is perfectly fine, if you handle the error. It just makes sure that the nasty include failed error isn't output if the configuration has such warnings turned on.
Yup, the exact reason I want to do this is to be able to handle the error ;)
5

Since include() returns false when fails, just check if it returns true and then do something like die() or show an error.

if (!include('page.php'))
   die('Error.');

1 Comment

If you're going to die, you might as well just use require though.
1

As Brendan Long's comment points out, if you're just wanting the script to stop running on a failed include, then you probably just want to be using require instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.