views:

573

answers:

3

Ok, I am creating an admin interface for my custom blog at the url /admin.

Is it possible for me to be able to use the same includes (including autoload), as the root directory.

If possible, I would also like to be able to automatically correct the links in the navigation so that they go that index.php in / changes to ../index.php when accessed from /admin.

Thanks, Nico

+3  A: 

The best practice for this is to define a 'ABSOLUTE_PATH' constant that contains the directory that everything is located under. After that, you can simply copy and paste everything, because it is defining the 'full' path, which doesn't change from directory to directory.

Example

define("ABS_PATH", $_SERVER['DOCUMENT_ROOT']);

or

define("ABS_PATH", dirname(__FILE__));
// This defines the path as the directory the file is in.

Then at any point you can simply do this to include a file

include(ABS_PATH . "/path/to/file");
Chacha102
ah, but how do I find out what this path should be?
Nico Burns
You probably want to take a look at PHP Info for a server variable, or define it yourself. If you define it yourself, make sure it is the directory that ALL files fall under.
Chacha102
+1  A: 

Easiest way would be to use absolute pathes / URLs.

For the URLs, define a constant/variable somewhere, that points to the root of your application, like :

define('ROOT_URL', 'http://www.example.com');

or

$root_url = 'http://www.example.com';

And use it in every link, like :

<a href="{$root_url}/my-page.php">blah</a>

This way, always OK (and the day you install your project on another server, or in a subdirectory, you only have one constant/variable to modify, and everything still works)

For includes / requires, always use absolute pathes too ; one solution is to use dirname, like this :

include dirname(__FILE__) . '/my_file.php';
include dirname(__FILE__) . '/../my-other-file.php';

__FILE__ is the current file, where you are writing this line ; dirname gets the path (the full path) to the directory containing that file.

With that, you never have to worry about the relative paths of your files.

Pascal MARTIN
+1 for absolute paths
Philippe Gerber
Do abs paths slow you down? Say if you're not just keeping your links straight, but down in program flow.
Smandoli
+1  A: 

Yet another answer would be similar to combining the first two suggestions. You could define the constant:

define('ABSPATH', dirname(FILE).'/');

Then, assuming that config.php needs to be included in many files of the site then you can use the following statement to accomplish this:

include(ABSPATH.'config.php');

Hope this helps -Ivan Novak

ivannovak