How to get the original path of a symbolic link in PHP? How to get the original path of a symbolic link in PHP? php php

How to get the original path of a symbolic link in PHP?


I just had a similar issue. You can do it by using $_SERVER['SCRIPT_FILENAME'] variable, that displays the requested file, so in your case it will be /mydocroot/include/somesubdir/include.inc.php, even if somesubdir is a symbolic link. To include a file that is one level lower instead of doing

require_once "../settings.inc.php";

do this:

require_once dirname(dirname($_SERVER['SCRIPT_FILENAME'])).DIRECTORY_SEPARATOR."settings.inc.php"

Documentation about $_SERVER variables


The most straight forward solution is to always use absolute paths. There are multiple ways you can do this, from hard coding the path every time you need it, to hard coding the path once in the top of your script and referencing that, to dynamically figuring it out and setting it once at the top of your script.

The third option is what most off the shelf CMSs use to be able to run without complete knowledge of your file structure.

Why is it that you're using a symbolically linked directory in this manner?


The solution is to create a basepath variable. The best way to do this is to include the following at the top of your script and then reference it

$basepath = dirname(dirname($_SERVER['SCRIPT_FILENAME'])).DIRECTORY_SEPARATOR;

You can then reference the basepath in your includes, requires, etc. Therefore,

include "../myscript.php";

Would become,

include $basepath."myscript.php";

If you are back ticking further, you will have this:

include "../../myscript.php";

Would become,

include $basepath."../myscript.php";

You must nest the dir_name functions twice, plus one more time for each additional folder you need to backtick through. You MUST get all the way back to the folder where the symbolic link exists.

I consider this issue a major design flaw with PHP. I can't think of a single instance where accessing backticked files relative to the actual file would be desirable. In all situations, including virtual hosting, it ONLY makes sense to regress back along the linked path, never the target path.