Check if an include (or require) exists

MintDeparture picture MintDeparture · Feb 12, 2010 · Viewed 80.2k times · Source

How do you check if an include / require_once exists before you call it, I tried putting it in an error block, but PHP didn't like that.

I think file_exists() would work with some effort, however that would require the whole file path, and a relative include could not be passed into it easily.

Are there any other ways?

Answer

Johannes Gorset picture Johannes Gorset · Feb 12, 2010

I believe file_exists does work with relative paths, though you could also try something along these lines...

if(!@include("script.php")) throw new Exception("Failed to include 'script.php'");

... needless to say, you may substitute the exception for any error handling method of your choosing. The idea here is that the if-statement verifies whether the file could be included, and any error messages normally outputted by include is supressed by prefixing it with @.