dongzong7467
dongzong7467
2014-06-04 14:32

获取当前php文件的目录,该文件自脚本开始运行后可能已更改

已采纳

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__ . "
";
    echo "__DIR__: " . __DIR__ . "
";
    echo "realpath(__FILE__): " . realpath(__FILE__) . "
";
    echo "realpath(__DIR__): " . realpath(__DIR__) . "
";
    echo '-----'. "
";
    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)?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douyao6842 douyao6842 7年前

    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.

    点赞 评论 复制链接分享
  • douliao1911 douliao1911 7年前
    dirname(__FILE__);
    

    Maybe this will be helpful?

    点赞 评论 复制链接分享