Reputation: 2156
I hope you can help. I need to find to way to get the current directory of the currently running PHP script.
The location of the script itself might have changed since the script was started.
I cannot use any magic constants such as __FILE__
or __DIR__
as a basis as they appear to be defined by the PHP processor at the beginning of execution and so continue to point to the original location of the script.
To test out ideas, I'm doing the following (from the command line on linux):
test.php
in directory test_1
i.e. test_1/test.php
php test_1/test.php
mv test_1 test_2
test_2
dir not test_1
The script used for this test was as follows:
<?php
while (true) {
echo "__FILE__: " . __FILE__ . "\n";
echo "__DIR__: " . __DIR__ . "\n";
echo "realpath(__FILE__): " . realpath(__FILE__) . "\n";
echo "realpath(__DIR__): " . realpath(__DIR__) . "\n";
echo '-----'. "\n";
sleep(5);
}
So, the question: How do you find out the current directory of the script running now (not where it was when the script started)?
Upvotes: 0
Views: 93
Reputation: 1494
The inode of a script will not change, even if it is moved to a different location in the same filesystem.
You could get the inode and pathname of the file at the beginning of the script, using the built-in function getmyinode:
<?php
$myinode = getmyinode();
$mypath = realpath(__FILE__);
?>
Then whenever you want to get the file path, call a function which compares the two and updates the path if necessary:
<?php
function getMyPath() {
global $myinode, $mypath;
if (fileinode($mypath) != $myinode) {
// File moved!
$searchfrom = '/'; // Maybe you can change this to $_SERVER['DOCUMENT_ROOT']
$mypath = shell_exec("find " . $searchfrom . " -inum " . $myinode . " -print -quit 2>/dev/null");
if (fileinode($mypath) != $myinode) {
// error; not found
}
}
return $mypath;
}
?>
It will be very slow to search for the inode if/when the file is moved but I don't see any way around that. Also note that if there are hardlinks then there could be multiple paths to the same file; the -print -quit
above simply stops after the first one.
This will only work on Linux due to the use of inodes and the find
shell command.
Upvotes: 1