How to set root folder for PHP include files
dirname(__FILE__)
and __DIR__
both same and __DIR__
comes with PHP 5.3
These are used in order to indicate that the "path of the file where they called".
URL: http://localhost/test/a.phpDIR: --NIX /var/www/test/a.php --WIN D:\lamp\www\test\a.php// a.php's inside<?phpecho __DIR__;
Gives you this on linux: /var/www/test
So, if you need a config parameter in all your project, just define it in your config.php and use it where you want both the file name that will be included.
./ config.php index.php header.php footer.php /lib foo.php /tmp bar.php
./config.phpdefine('ROOT', __DIR__ .'/');
./index.php include_once(ROOT .'header.php'); ... include_once(ROOT .'footer.php');
i.e, using it in tmp dir
./tmp/bar.php include_once(ROOT .'lib/foo.php');
UPDATE
// config.php<?phpdefine("ROOT", __DIR__ ."/");
So, we use this for index.php
to include banner.php
and banner.php
is waiting in ./banners/banner.php
;
// index.php and the very first line!<?phpinclude_once("config.php");?>// some html stuff// ...<?php include_once(ROOT ."banners/banner.php"); ?>// some more html stuff// ...
So, you should include config.php first to where you need it.
I think, this is basic as far as needed...
UPDATE
So your problem is not PHP include
system, but question, anyway... :)
If your image path is changing (so not fixed), you can do like this;
// config.phpdefine("ROOT", __DIR__ ."/");define("HTTP", ($_SERVER["SERVER_NAME"] == "localhost") ? "http://localhost/your_work_folder/" : "http://your_site_name.com/");// banner.php<img src="<?php print HTTP; ?>images/banner.gif">
I normally set up what you mentioned, a config.php in an include directory, and have the following line in it: define('BASE_PATH', str_replace('/include', '', dirname(__FILE__)));
("/include should be whatever directory your config.php file is in, if you have it in the root directory, you can just use define('BASE_PATH', dirname(__FILE__));
). When I want to include any other file after that, I use include_once(BASE_PATH . '/directory/file.php');
.
note: this concept is not original to me by any means.
There is a function called getcwd()
which will return the current working folder. If you call this at the very beginning of your script, you can store this, usually into a constant with define()
.
define('PROJECT_ROOT', getcwd());