How to get the absolute path to the public_html fo

2019-01-17 07:10发布

$_SERVER['DOCUMENT_ROOT']

returns

/usr/local/apache/htdocs/

is there a way to get

/home/user/public_html/

The problem is that I have to write a script which can be in the public_html folder or a sub-folder of the public_html folder. The script should save uploaded files into a folder inside public_html directory(say images). In other words let us say that my file is test.php and the path to it is

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

And there is a folder

/home/user/public_html/images 

where files uploaded via test.php have to be saved. I don't know where the test.php file will be run. For example it can be at the path

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

How do I get the path to the images folder without knowing where the test.php file will be?

9条回答
2楼-- · 2019-01-17 07:15

Whenever you want any sort of configuration information you can use phpinfo().

查看更多
混吃等死
3楼-- · 2019-01-17 07:15

with preg_replace function to find absolute path from __FILE__ you can easily find with anything home user. Here short my code :

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

查看更多
▲ chillily
4楼-- · 2019-01-17 07:16

put anyfile on the directories you wanted to find, in this case, place 'root' at public_html

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

And use this function

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.="../";
        }
    }
}

and get the value by calling it

$pathToRoot = findThis('root');

And it will return, for example the the dir of php script is

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

so the $pathToRoot will be

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

Is this the one you want??

查看更多
来,给爷笑一个
5楼-- · 2019-01-17 07:16

You can also use dirname in dirname to get to where you want to be.

Example of usage:

For Joomla, modules will always be installed in /public_html/modules/mod_modulename/

So, from within a file within the module's folder, to get to the Joomla install-root on any server , I could use: $path = dirname(dirname(dirname(__FILE__)));

The same goes for Wordpress, where plugins are always in wp-content/plugins/

Hope this helps someone.

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-17 07:17

Let's asume that show_images.php is in folder images and the site root is public_html, so:

echo dirname(__DIR__); // prints '/home/public_html/'
echo dirname(__FILE__); // prints '/home/public_html/images'
查看更多
我命由我不由天
7楼-- · 2019-01-17 07:18

Out of curiosity, why don't you just use the url for the said folder?

http://www.mysite.com/images

Assuming that the folder never changes location, that would be the easiest way to do it.

查看更多
登录 后发表回答