Get parent directory of running script

后端 未结 13 2064
攒了一身酷
攒了一身酷 2020-11-30 04:20

In PHP, what would be the cleanest way to get the parent directory of the current running script relative to the www root? Assume I have:

$_         


        
13条回答
  •  佛祖请我去吃肉
    2020-11-30 04:55

    If your script is located in /var/www/dir/index.php then the following would return:

    dirname(__FILE__); // /var/www/dir
    

    or

    dirname( dirname(__FILE__) ); // /var/www
    

    Edit

    This is a technique used in many frameworks to determine relative paths from the app_root.

    File structure:

     /var/
          www/
              index.php
              subdir/
                     library.php
    

    index.php is my dispatcher/boostrap file that all requests are routed to:

    define(ROOT_PATH, dirname(__FILE__) ); // /var/www
    

    library.php is some file located an extra directory down and I need to determine the path relative to the app root (/var/www/).

    $path_current = dirname( __FILE__ ); // /var/www/subdir
    $path_relative = str_replace(ROOT_PATH, '', $path_current); // /subdir
    

    There's probably a better way to calculate the relative path then str_replace() but you get the idea.

提交回复
热议问题