note 23936 added to function.dirname
| From: | rwf at gpcom dot net | Date: | Thu, 01 Aug 2002 20:08:01 +0000 |
| Subject: | note 23936 added to function.dirname | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-34103@lists.php.net to get a copy of this message | ||
If you want relative includes like C or C++ has, you need to find out where you are in relation to
the base path of the server. That is, if you are two levels into the "htdocs" directory in
apache, then you need to add "../../" to the begining of the include to get back to the
base directory. That's simple. What's NOT so simple is when you have "nested"
included files.
Continuing the example above, if you have a file example.php and it includes
"../../lib.php" and lib.php includes "lib2.php" guess where "lib2.php"
needs to be located? In the same directory as example.php! What you really wanted was to have
lib.php and lib2.php in the same directory... To get that result you need to include
"../../lib2.php" in lib.php... But wait, now it won't work if the original
example.php file is in any other place but two levels deep!
The answer to the problem is this: find the number of levels you are currently into the base
directory and add as many "../" as you need to the begining of the include filename in
EVERY include file.
Here's an example:
example.php
------------
$BasePath = str_repeat("../", substr_count(dirname($_SERVER["SCRIPT_NAME"]),
"/"));
require_once($BasePath."lib.php");
------------
Notice that we're adding the $BasePath and the name of the file we want together to get the
full path. It will look like this: "../../lib.php"
lib.php
------
require_once($BasePath."lib2.php");
------
Notice here that BasePath has already been defined so we don't know or care what BasePath looks
like, only that it now allows us to use a relative path to lib2.php since it automatically adds the
number of "../" needed to get to it from the original example.php that the server
executed. The path here will look like this: "../../lib2.php"
And now we can easily have lib.php and lib2.php in the same directory, and have lib.php include
lib2.php as if it's a relative include.
Pretty simple, no? :)
-Fredric Echols
--
http://www.php.net/manual/en/function.dirname.php
http://master.php.net/manage/user-notes.php?action=edit+23936
http://master.php.net/manage/user-notes.php?action=delete+23936
http://master.php.net/manage/user-notes.php?action=reject+23936