How to include PHP files that require an absolute path?

php

Question

I have a directory structure like the following;

script.php

inc/include1.php
inc/include2.php

objects/object1.php
objects/object2.php

soap/soap.php

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]/"?

1
91
6/4/2019 9:29:07 AM

Accepted Answer

This should work

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

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

Edit: added imporvement by aussieviking

146
5/23/2017 11:47:20 AM

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. (source)

Another solution would be to set an include path in your httpd.conf or an .htaccess file.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon