views:

309

answers:

3

Hi,

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?

+3  A: 

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 @.

Johannes Gorset
file exists works with relatives paths
solomongaby
You don’t need the parentheses around the argument value of `include`. `include` is not a function but a language construct like `echo`.
Gumbo
@Gumbo I consider it good practice to use parantheses for language constructs, much like I do with `echo()` and `print()` as well.
Johannes Gorset
A: 

file_exists would work with checking if the required file exists when it is relative to the current working directory as it works fine with relative paths. However, if the include file was elsewhere on PATH, you would have to check several paths.

function include_exists ($fileName){
    if (realpath($fileName) == $fileName) {
        return is_file($fileName);
    }
    if ( is_file($fileName) ){
        return true;
    }

    $paths = explode(PS, get_include_path());
    foreach ($paths as $path) {
        $rp = substr($path, -1) == DS ? $path.$fileName : $path.DS.$fileName;
        if ( is_file($rp) ) {
            return true;
        }
    }
    return false;
}
Yacoby
file_exists can't search in the include paths. You would have to parse them manually.
Petr Peller
@Petr thanks for pointing that out, fixed.
Yacoby
A: 

file_exists() works with relative paths, it'll also check if directories exist. Use is_file() instead:

if (is_file('./path/to/your/file.php'))
{
    require_once('./path/to/your/file.php');
}
Alix Axel
While it works with relative paths, it does not work with include paths -- something to note ;)
Billy ONeal