Home » Questions » Computers [ Ask a new question ]

How to include PHP files that require an absolute path?

How to include PHP files that require an absolute path?

"I have a directory structure like the following;





Now, I use those objects in both script.php and /soap/soap.php, I could move them, but I want the directory structure like that for a specific reason. When executing script.php the include path is inc/include.php and when executing /soap/soap.php it's ../inc, absolute paths work, /mnt/webdev/[project name]/inc/include1.php... But it's an ugly solution if I ever want to move the directory to a different location.

So is there a way to use relative paths, or a way to programmatically generate the ""/mnt/webdev/[project name]/""?"

Asked by: Guest | Views: 58
Total answers/comments: 5
Guest [Entry]

"This should work

$root = realpath($_SERVER[""DOCUMENT_ROOT""]);

include ""$root/inc/include1.php"";

Edit: added imporvement by aussieviking"
Guest [Entry]

"You can use relative paths. Try __FILE__. This is a PHP constant which always returns the path/filename of the script it is in. So, in soap.php, you could do:

include dirname(__FILE__).'/../inc/include.php';

The full path and filename of the
file. If used inside an include, the
name of the included file is returned.
Since PHP 4.0.2, __FILE__ always
contains an absolute path with
symlinks resolved whereas in older
versions it contained relative path
under some circumstances.

Another solution would be to set an include path in your httpd.conf or an .htaccess file."
Guest [Entry]

"Another way to handle this that removes any need for includes at all is to use the autoload feature. Including everything your script needs ""Just in Case"" can impede performance. If your includes are all class or interface definitions, and you want to load them only when needed, you can overload the __autoload() function with your own code to find the appropriate class file and load it only when it's called. Here is the example from the manual:

function __autoload($class_name) {
require_once $class_name . '.php';

$obj = new MyClass1();
$obj2 = new MyClass2();

As long as you set your include_path variables accordingly, you never need to include a class file again."
Guest [Entry]

have a look at http://au.php.net/reserved.variables
Guest [Entry]

You could define a constant with the path to the root directory of your project, and then put that at the beginning of the path.