views:

62

answers:

3

In many places in my code, I do things like:

file1.php:
<?php
include('../file2.php');

file2.php:
<?php
include('anotherdirectory/file3.php');

Depending on the server or settings I try this on, it either sets the relative paths from the "includer" or from the "includee". This is really confusing. So file1 might try to include "../anotherdirectory/file3.php" or it might try "anotherdirectory/file3.php".

What settings dictate this behavior? I want to have control over this...

+3  A: 

I would recommend using absolute paths. A good way to do this while still being portable is to make a declaration like this in your public_html/index.php:

define('ROOT', dirname(__FILE__));

Then, you can write includes like this which are very easy:

include(ROOT.'/file.php');

Otherwise, PHP checks to see if the file is in the include path as defined by your php.ini. If it's not there, it tries a relative path to the current script. Which is unpredictable and unmaintainable since you may be nestingly including files from different relative locations.

Edit: If you're constantly including a lot of class files, you may want to look into autoloading. It makes everything way simpler if you're programming in an object-oriented style. I have personally never written the word 'include' in my code for a very long time.

Edit 2: You could use the php.ini directive auto_prepend_file to automatically include a one-line file with the definition of ROOT to each one of your scripts.

Lotus Notes
Please provide reason for downvote, I would be open to learning better methods.
Lotus Notes
But then I would have to include the file that will have this "define()". So I'd be back to the same problem.
nute
Good point. Optimally, your index.php would route all requests to the appropriate script using mod_rewrite, but this is another question in itself. Almost every MVC (Model-View-Controller) application does this.
Lotus Notes
In a perfect world, I would have built my 7 years old app as a MVC :) But thanks.
nute
Edited my answer for another possible solution with auto_prepend_file.
Lotus Notes
A: 

In cases when I need to use relative paths I use the following syntax:

include (realpath(dirname(__FILE__)."/another_folder/myfile.php");
a1ex07
A: 

With get_include_path() you can see, what the server configuration for this is. In most cases it looks like this:

.:/usr/lib/php

This means, the first place php is looking for a included file is the directory of the script that includes another. If it is not present there, php is looking in /usr/php/lib. If you add more paths, php will also look there for a matching file.

If you include a file, which includes another one, the "root" path is the path of the file which included another one at first.

unset