如何获取public_html文件夹的绝对路径?

时间:2011-05-21 03:49:06

标签: php public-html

$_SERVER['DOCUMENT_ROOT']

返回

/usr/local/apache/htdocs/

有办法获得

/home/user/public_html/

问题是我必须编写一个脚本,该脚本可以位于public_html文件夹或public_html文件夹的子文件夹中。该脚本应将上传的文件保存到public_html目录(例如图像)中的文件夹中。换句话说,让我们说我的文件是test.php,它的路径是

/home/user/public_html/test/test.php. 

还有一个文件夹

/home/user/public_html/images 

必须保存通过test.php上传的文件。我不知道test.php文件将在哪里运行。例如,它可以在路径

/home/user/public_html/test/another-dir/test.php

如何在不知道test.php文件的位置的情况下获取images文件夹的路径?

11 个答案:

答案 0 :(得分:36)

我今天发现的东西,在读完这个问题并继续我的googlesurf之后:

https://docs.joomla.org/How_to_find_your_absolute_path

<?php
$path = getcwd();
echo "This Is Your Absolute Path: ";
echo $path;
?>

适合我

答案 1 :(得分:20)

您正在运行的文件在哪里?如果它位于您的公共html文件夹中,则可以执行echo dirname(__FILE__);

答案 2 :(得分:9)

让我们假设show_images.php位于文件夹images中,网站根目录为public_html,所以:

echo dirname(__DIR__); // prints '/home/public_html/'
echo dirname(__FILE__); // prints '/home/public_html/images'

答案 3 :(得分:3)

将anyfile放在你想要找到的目录上,在这种情况下,将'root'放在public_html

/home/user/public_html/root <- note that 'root' is not a folder (you can use root.txt if u want)

并使用此功能

function findThis($get){
    $d = '';
    for($i = 0; $i < 20; $i++){//this will try 20 times recursively on upper folder
        if(file_exists($d.$get)){
            return $d;
        }else{
            $d.="../";
        }
    }
}

并通过调用来获取值

$pathToRoot = findThis('root');

它会返回,例如php脚本的目录是

/home/user/public_html/test/another-dir/test.php

所以$ pathToRoot将是

$pathToRoot => "../../../"

这是你想要的吗?

答案 4 :(得分:3)

每当您需要任何类型的配置信息时,都可以使用phpinfo()

答案 5 :(得分:2)

出于好奇,为什么不直接使用该文件夹的网址?

http://www.mysite.com/images

假设文件夹永远不会改变位置,那将是最简单的方法。

答案 6 :(得分:1)

这是超级老,但我遇到了它,这对我有用。

<?php
//Get absolute path
$path = getcwd();
//strip the path at your root dir name and everything that follows it
$path = substr($path, 0, strpos($path, "root"));
echo "This Is Your Absolute Path: ";
echo $path; //This will output /home/public_html/
?>

答案 7 :(得分:0)

使用preg_replace函数查找__FILE__的绝对路径,您可以轻松找到任何家庭用户。这里简短的代码:

  

$ path_image_you_want = preg_replace('#/ public_html /([^/]+?)/.*#',   '/ public_html / $ 1 / images“,__FILE__);

答案 8 :(得分:0)

您也可以在dirname中使用dirname来到达您想要的位置。

使用示例:

对于Joomla,模块将始终安装在/public_html/modules/mod_modulename/

因此,在模块文件夹中的文件中,要在任何服务器上访问Joomla install-root,我可以使用: $path = dirname(dirname(dirname(__FILE__)));

Wordpress也是如此,其中插件始终位于wp-content/plugins/

希望这有助于某人。

答案 9 :(得分:0)

<?php

    // Get absolute path
    $path = getcwd(); // /home/user/public_html/test/test.php.   

    $path = substr($path, 0, strpos($path, "public_html"));

    $root = $path . "public_html/";

    echo $root; // This will output /home/user/public_html/

答案 10 :(得分:0)

您只需要创建一个偏移量旁路即可将您希望向后的读数移动到多远。因此,我们使用getcwd()来获取路径并爆炸(拆分为数组)以获取$root和路径结尾之间的数据。

function getRoot($root = "public_html") {
    return explode($root, getcwd())[0].$root."/";
}