I have long kept everything except directly viewable scripts outside the web root. Then configure PHP to include your script directory in the path. A typical set up would be:
appdir
include
html
In the PHP config (either the global PHP config or in a .htaccess
file in the html
directory) add this:
include_path = ".:/path/to/appdir/include:/usr/share/php"
or (for Windows)
include_path = ".;c:\path\to\appdir\include;c:\php\includes"
Note that this line is probably already in your php.ini
file, but may be commented out allowing the defaults to work. It might also include other paths. Be sure to keep those, as well.
If you are adding it to a .htaccess file, the format is:
php_value include_path .:/path/to/appdir/include:/usr/share/php
Finally, you can add the path programatically with something like this:
$parentPath = dirname(dirname(__FILE__));
$ourPath = $parentPath . DIRECTORY_SEPARATOR . 'include';
$includePath = ini_get('include_path');
$includePaths = explode(PATH_SEPARATOR, $includePath);
// Put our path between 'current directory' and rest of search path
if ($includePaths[0] == '.') {
array_shift($includePaths);
}
array_unshift($includePaths, '.', $ourPath);
$includePath = implode(PATH_SEPARATOR, $includePaths);
ini_set('include_path', $includePath);
(Based on working code, but modified, so untested)
This should be run in your frontend file (e.g. index.php
). I put it in a separate include file which, after modifying the above, can be included with something like #include '../includes/prepPath.inc'
.
I've used all the versions I've presented here with success. The particular method used depends on preferences, and how the project will be deployed. In other words, if you can't modify php.ini
, you obviously can't use that method