Reputation: 1221
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 adapted it from a Lynda tutorial)
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('SITE_ROOT') ? null :
define('SITE_ROOT', 'C:'.DS.'wamp'.DS.'www'.DS.'ArmyCreator');
defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes');
defined('PUB_PATH') ? null : define('PUB_PATH', SITE_ROOT.DS.'public');
// load config file first
require_once(LIB_PATH.DS."helper".DS.'config.php');
Now since I am deploying my webiste I can't figure out how to declare the SITE_ROOt to make it work properly?
EDIT
Is it normal for code like this: require_once("../../includes/helper/initialize.php");
to not work anymore once I deploy to the website?
Upvotes: 0
Views: 6518
Reputation: 165193
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
Upvotes: 1
Reputation: 7993
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.
Upvotes: 1
Reputation: 24234
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
.
Upvotes: 0
Reputation: 8915
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
Upvotes: 6