Luke Cousins
Luke Cousins

Reputation: 2156

Get directory of current php file, which might have changed since the script started to run

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):

  1. Have a file named test.php in directory test_1 i.e. test_1/test.php
  2. Run this file on the command line with: php test_1/test.php
  3. Open another terminal session and rename the directory with mv test_1 test_2
  4. Keep an eye on the original terminal and hope you can find that it is reporting the new 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

Answers (2)

Dan R
Dan R

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

kot-6eremot
kot-6eremot

Reputation: 71

dirname(__FILE__);

Maybe this will be helpful?

Upvotes: 0

Related Questions