获取运行脚本的父目录

时间:2021-10-01 07:08:04

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:

在PHP中,获取当前运行脚本相对于www根的父目录的最干净的方法是什么?假设我有:

$_SERVER['SCRIPT_NAME'] == '/relative/path/to/script/index.php'

Or just:

或者是:

$something_else == '/relative/path/to/script/'

And I need to get /relative/path/to/ with slashes properly inserted. What would you suggest? A one liner is preferred.

我需要得到/相对/路径/到/用斜线正确插入。你建议什么?最好是一个衬垫。

EDIT

编辑

I need to get a path relative to the www root, dirname(__FILE__) gives me an absolute path in the filesystem so that won't work. $_SERVER['SCRIPT_NAME'] on the other hand 'starts' at the www root.

我需要找到一个相对于www根的路径,dirname(__FILE__)在文件系统中提供了一个绝对路径,这样就不工作了。另一方面,$_SERVER['SCRIPT_NAME']在www根上' started '。

13 个解决方案

#1


114  

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

如果您的脚本位于/var/www/ dir/index.0。php则返回:

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.

这是许多框架中用于确定来自app_root的相对路径的技术。

File structure:

文件结构:

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

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

索引。php是我的dispatcher/boostrap文件,所有请求都被路由到:

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/).

图书馆。php是一些文件,它位于一个额外的目录下,我需要确定相对于应用程序根的路径(/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.

可能有一种更好的方法来计算相对路径然后str_replace(),但是您应该明白了。

#2


13  

As of PHP 5.3.0 you can use __DIR__ for this purpose.

从PHP 5.3.0开始,您就可以为此使用__DIR__了。

The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__ FILE__).

文件的目录。如果在包含中使用,则返回包含文件的目录。这相当于dirname(__文件__)。

See PHP Magic constants.

看到PHP魔术常量。

C:\www>php --version
PHP 5.5.6 (cli) (built: Nov 12 2013 11:33:44)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies

C:\www>php -r "echo __DIR__;"
C:\www

#3


7  

If I properly understood your question, supposing your running script is

如果我正确地理解了你的问题,假设你的运行脚本是

/relative/path/to/script/index.php

This would give you the parent directory of your running script relative to the document www:

这将为您提供与www文档相关的运行脚本的父目录:

$parent_dir = dirname(dirname($_SERVER['SCRIPT_NAME'])) . '/';
//$parent_dir will be '/relative/path/to/'

If you want the parent directory of your running script relative to server root:

如果您希望运行脚本的父目录相对于服务器根目录:

$parent_dir = dirname(dirname($_SERVER['SCRIPT_FILENAME'])) . '/';
//$parent_dir will be '/root/some/path/relative/path/to/'

#4


7  

To get the parentdir of the current script.

获取当前脚本的parentdir。

$parent_dir = dirname(__DIR__);

#5


5  

Fugly, but this will do it:

很糟,但这就行了:

substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'],basename($_SERVER['SCRIPT_NAME'])))

#6


2  

$dir = dirname($file) . DIRECTORY_SEPARATOR;

#7


1  

Here is what I use since I am not running > 5.2

这里是我使用的,因为我没有运行> 5.2

function getCurrentOrParentDirectory($type='current')
{
    if ($type == 'current') {
        $path = dirname(__FILE__);  
    } else {
        $path = dirname(dirname(__FILE__));
    }
    $position = strrpos($path, '/') + 1;
    return substr($path, $position);
}

Double dirname with file as suggested by @mike b for the parent directory, and current directory is found by just using that syntax once.

使用@mike b建议的父目录的文件的双dirname,并且只使用该语法一次就可以找到当前目录。

Note this function only returns the NAME, slashes have to be added afterwards.

注意,此函数只返回名称,之后必须添加斜线。

#8


1  

Try this. Works on both windows or linux server..

试试这个。适用于windows或linux服务器。

str_replace('\\','/',dirname(dirname(__FILE__)))

(大小写不敏感' \ \ ',' / ',目录名(目录名(__FILE__)))

#9


1  

I Hope this will help you.

我希望这能对你有所帮助。

echo getcwd().'<br>'; // getcwd() will return current working directory
echo dirname(getcwd(),1).'<br>';
echo dirname(getcwd(),2).'<br>';
echo dirname(getcwd(),3).'<br>';

Output :

输出:

C:\wamp64\www\public_html\step
C:\wamp64\www\public_html
C:\wamp64\www
C:\wamp64

#10


0  

This is also a possible solution

这也是一种可能的解决方案

$relative = '/relative/path/to/script/';
$absolute = __DIR__. '/../' .$relative;

#11


0  

This is a function that I use. Created it once so I always have this functionality:

这是我使用的函数。创建了一次,所以我总是有这个功能:

function getDir(){
    $directory = dirname(__FILE__);
    $directory = explode("/",$directory);
    $findTarget = 0;
    $targetPath = "";
    foreach($directory as $dir){
        if($findTarget == 1){
            $targetPath = "".$targetPath."/".$dir."";
        }
        if($dir == "public_html"){
            $findTarget = 1;
        }
    }
    return "http://www.".$_SERVER['SERVER_NAME']."".$targetPath."";
}

#12


0  

I hope this will help

我希望这能有所帮助。

function get_directory(){
    $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
    $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol . "://" . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);
}
define("ROOT_PATH", get_directory()."/" );
echo ROOT_PATH;

#13


-6  

Got it myself, it's a bit kludgy but it works:

我自己弄的,有点笨拙,但很管用:

substr(dirname($_SERVER['SCRIPT_NAME']), 0, strrpos(dirname($_SERVER['SCRIPT_NAME']), '/') + 1)

So if I have /path/to/folder/index.php, this results in /path/to/.

如果我有/path/to/文件夹/索引。php,这将导致/path/to/。

#1


114  

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

如果您的脚本位于/var/www/ dir/index.0。php则返回:

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.

这是许多框架中用于确定来自app_root的相对路径的技术。

File structure:

文件结构:

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

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

索引。php是我的dispatcher/boostrap文件,所有请求都被路由到:

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/).

图书馆。php是一些文件,它位于一个额外的目录下,我需要确定相对于应用程序根的路径(/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.

可能有一种更好的方法来计算相对路径然后str_replace(),但是您应该明白了。

#2


13  

As of PHP 5.3.0 you can use __DIR__ for this purpose.

从PHP 5.3.0开始,您就可以为此使用__DIR__了。

The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__ FILE__).

文件的目录。如果在包含中使用,则返回包含文件的目录。这相当于dirname(__文件__)。

See PHP Magic constants.

看到PHP魔术常量。

C:\www>php --version
PHP 5.5.6 (cli) (built: Nov 12 2013 11:33:44)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies

C:\www>php -r "echo __DIR__;"
C:\www

#3


7  

If I properly understood your question, supposing your running script is

如果我正确地理解了你的问题,假设你的运行脚本是

/relative/path/to/script/index.php

This would give you the parent directory of your running script relative to the document www:

这将为您提供与www文档相关的运行脚本的父目录:

$parent_dir = dirname(dirname($_SERVER['SCRIPT_NAME'])) . '/';
//$parent_dir will be '/relative/path/to/'

If you want the parent directory of your running script relative to server root:

如果您希望运行脚本的父目录相对于服务器根目录:

$parent_dir = dirname(dirname($_SERVER['SCRIPT_FILENAME'])) . '/';
//$parent_dir will be '/root/some/path/relative/path/to/'

#4


7  

To get the parentdir of the current script.

获取当前脚本的parentdir。

$parent_dir = dirname(__DIR__);

#5


5  

Fugly, but this will do it:

很糟,但这就行了:

substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'],basename($_SERVER['SCRIPT_NAME'])))

#6


2  

$dir = dirname($file) . DIRECTORY_SEPARATOR;

#7


1  

Here is what I use since I am not running > 5.2

这里是我使用的,因为我没有运行> 5.2

function getCurrentOrParentDirectory($type='current')
{
    if ($type == 'current') {
        $path = dirname(__FILE__);  
    } else {
        $path = dirname(dirname(__FILE__));
    }
    $position = strrpos($path, '/') + 1;
    return substr($path, $position);
}

Double dirname with file as suggested by @mike b for the parent directory, and current directory is found by just using that syntax once.

使用@mike b建议的父目录的文件的双dirname,并且只使用该语法一次就可以找到当前目录。

Note this function only returns the NAME, slashes have to be added afterwards.

注意,此函数只返回名称,之后必须添加斜线。

#8


1  

Try this. Works on both windows or linux server..

试试这个。适用于windows或linux服务器。

str_replace('\\','/',dirname(dirname(__FILE__)))

(大小写不敏感' \ \ ',' / ',目录名(目录名(__FILE__)))

#9


1  

I Hope this will help you.

我希望这能对你有所帮助。

echo getcwd().'<br>'; // getcwd() will return current working directory
echo dirname(getcwd(),1).'<br>';
echo dirname(getcwd(),2).'<br>';
echo dirname(getcwd(),3).'<br>';

Output :

输出:

C:\wamp64\www\public_html\step
C:\wamp64\www\public_html
C:\wamp64\www
C:\wamp64

#10


0  

This is also a possible solution

这也是一种可能的解决方案

$relative = '/relative/path/to/script/';
$absolute = __DIR__. '/../' .$relative;

#11


0  

This is a function that I use. Created it once so I always have this functionality:

这是我使用的函数。创建了一次,所以我总是有这个功能:

function getDir(){
    $directory = dirname(__FILE__);
    $directory = explode("/",$directory);
    $findTarget = 0;
    $targetPath = "";
    foreach($directory as $dir){
        if($findTarget == 1){
            $targetPath = "".$targetPath."/".$dir."";
        }
        if($dir == "public_html"){
            $findTarget = 1;
        }
    }
    return "http://www.".$_SERVER['SERVER_NAME']."".$targetPath."";
}

#12


0  

I hope this will help

我希望这能有所帮助。

function get_directory(){
    $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
    $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol . "://" . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);
}
define("ROOT_PATH", get_directory()."/" );
echo ROOT_PATH;

#13


-6  

Got it myself, it's a bit kludgy but it works:

我自己弄的,有点笨拙,但很管用:

substr(dirname($_SERVER['SCRIPT_NAME']), 0, strrpos(dirname($_SERVER['SCRIPT_NAME']), '/') + 1)

So if I have /path/to/folder/index.php, this results in /path/to/.

如果我有/path/to/文件夹/索引。php,这将导致/path/to/。