简体   繁体   中英

php get the root of the file

how can i get the root to the main folder? for example i run file in this location :

public_html/admin/user/etc/index.php

and i want to include file from

public_html/includes/user/etc/function.php

so i want to do something like this:

include(get_first_default_folder().'includes/user/etc/function.php');

instead of:

include('../../../includes/user/etc/function.php');

You can use Document root from $_SERVER['DOCUMENT_ROOT'].

You can include this line in your index.php file.

include("{$_SERVER['DOCUMENT_ROOT']}includes/user/etc/function.php");

I normally do this thusly. $myDir = dirname(__FILE__); (or you can use __DIR__ on PHP v5.3+) is the directory name that the particular file is in. You know where in the hierarchy this is, so you can easily get the base with $myBaseDir = realpath('../../../'.$mydir) '. Realpath expands the path to it's canonical version, not including any symbolic links. Having the full path can also allows for a small speedup when it comes to including or otherwise finding files.

The reason I do that, rather than using $_SERVER['DOCUMENT_ROOT'] , is that that environment variable probably won't exist if I'm running a script from the command line - it's set by the webserver.

This a bit clumsy approach I guess but it works for me. On the beginning of every file I define a variable $root . First level variable is $root = './' (this is not required thought), first subfolder is $root = '../' , second subfolder is $root = '../../' and so forth. $root always takes me to the root folder of my site.

When I need to provide a path I just do something like include("{$root}includes/user/etc/function.php");

This helped me to get rid of "no such index or file" warnings so I'll stick with it until I find a better way of doing the same thing.

Alternatively you could define a constant for each folder level so you don't have to add $root at the top of the every file. (Haven't tested it so I don't know if the following syntax is correct.) Instead you'd do something like:

  • {ROOT}includes/user/etc/function.php");` // root level files
  • {SUBFOLDER_LEVEL_ONE}includes/user/etc/function.php");` // first subfolder level files

After defining the constants somewhere:

  • define("ROOT", "./");
  • define("SUBFOLDER_LEVEL_ONE", "../");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM