When developing my website I called all the includes in my php files by calling one single file called includes.
The code of this file looked somethig like this: (I
First off: I'd drop the DS, it's BS (ehe). Windows support both C:/wamp/www
and C:\wamp\www
:-) Even C:\wamp\www/project
is fine.
If includes.php
is located in, say lib/includes.php
(relative to your project root), then do this:
define('SITE_ROOT', realpath('../'));
That will dynamically set SITE_ROOT
.
Two suggestions here:
You're going to want SITE_ROOT
to be absolute path of the directory your files are located in. For example, in the above code, this directory is C:\wamp\www\ArmyCreator
. You can define this manually if you know the directory, or dynamically by using the predefined __DIR__
constant (PHP 5.3+), or dirname(__FILE__)
if you're not on 5.3 yet.
Including a bunch of files all at once in generally considered bad practice, and autoloading should be used instead. This will give you better performance as well as a well-defined directory layout and naming scheme, leading to better code. To do this, you can use the spl_autoload_register() function.
First off, don't abuse ternary syntax like that. Instead of defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
, you can use the OR
operator (which will short-circuit on a boolean true result):
defined('DS') OR define('DS', DIRECTORY_SEPARATOR);
Secondly, if this is inside of a bootstrap file that you know the position of, simply use dirname(__FILE__)
:
defined('SITE_ROOT') OR define('SITE_ROOT', dirname(__FILE__));
Otherwise, if you know the relative position of the root, you can use multiple dirname
calls. So if it's the parent directory of the present one:
defined('SITE_ROOT') OR define('SITE_ROOT', dirname(dirname(__FILE__)));
Don't use $_SERVER['DOCUMENT_ROOT']
or cwd()
or hardcode your path. Always use dirname(__FILE__)
to determine the absolute path. For more info on why, see This Answer
You can include the files relative to includes.php's directory by doing:
<?
$basePath = dirname(__FILE__);
require_once($basePath . "relative/path/from/basePath"); // replace the string with your real relative path