Finding PHP included files from several places

Submitted by kitt on Thu, 2005-04-21 23:22.

Depending on how the include path is constructed for a PHP application, a file may or may not exist in the include path. A developer may, for example, wish to check several locations for a file to be included, and stop processing a PHP file if the file cannot be found.

We came across this issue when trying to include the Smarty Template base class, Smarty.class.php

The file could be in one of two locations, depending on the include path, which was not standardized across our development and test machines. The file was either directly in the path, or in the Smarty directory, which was in the path.

So, we used this line:

@(include_once('Smarty.class.php')) OR require_once('Smarty/Smarty.class.php');

The first include_once will look for the Smarty file on the current include path. include_once and include do not stop the script execution on failure, whereas require will.

The @ in front of the include_once will suppress errors, including those output to screen. So, if the first include fails, the require_once comes into effect. The script will try to locate the Smarty file in the Smarty subdirectory.

Now, if the file is not found in either location, we do want the script to stop execution, so we use require_once for the second include.

We could also chain several include statements together, if needed, suppressing errors as needed until success or complete failure.