PHP how to find application root?

眉间皱痕 提交于 2019-11-28 19:15:01
Jonathan Kuhn

There is $_SERVER['DOCUMENT_ROOT'] that should have the root path to your web server.

Edit: If you look at most major php programs. When using the installer, you usually enter in the full path to the the application folder. The installer will just put that in a config file that is included in the entire application. One option is to use an auto prepend file to set the variable. another option is to just include_once() the config file on every page you need it. Last option I would suggest is to write you application using bootstrapping which is where you funnel all requests through one file (usually with url_rewrite). This allows you to easily set/include config variables in one spot and have them be available throughout all the scripts.

barbushin

I usually store config.php file in ROOT directory, and in config.php I write:

define('ROOT_DIR', __DIR__);

And then just use ROOT_DIR constant in all other scripts. Using $_SERVER['DOCUMENT_ROOT'] is not very good because:

  • It's not always matching ROOT_DIR
  • This variable is not available in CGI mode (e.x. if you run your scripts by CRON)

You should use the built in magic constants to find files. __FILE__ and __DIR__. If you are on PHP < 5.3 you should use dirname(__FILE__)

E.g.

require_once __DIR__.'/../../include_me.php';

$_SERVER['DOCUMENT_ROOT'] is not always guaranteed to return what you would expect.

It's nice to be able to use the same code at the top of every script and know that your page will load properly, even if you are in a subdirectory. I use this, which relies on you knowing what your root directory is called (typically, 'htdocs' or 'public_html':

defined('SITEROOT') or define('SITEROOT', substr($_SERVER['DOCUMENT_ROOT'], 0, strrpos($_SERVER['DOCUMENT_ROOT'], 'public_html')) . 'public_html');

With SITEROOT defined consistently, you can then access a config file and/or page components without adapting paths on a script-by-script basis e.g. to a config file stored outside your root folder:

require_once SITEROOT . "/../config.php";

Define it in a config file somewhere.

Assuming you're using an MVC style where everything gets routed through a single index.php then

realpath('.');

Will show you the path to the current working directory (i.e where index.php is)

So then you can define this as

define('PROJECT_ROOT', realpath('.'));

If it's not MVC and you need it to work for files in subfolders then you can just hard code it in a config file

define('PROJECT_ROOT', 'C:/wamp/www/mysite');

Then when including something you can do;

include PROJECT_ROOT . '/path/to/include.php';

You could alternativly set the base directory in your .htaccess file

SetEnv BASE_PATH C:/wamp/www/mysite/

Then in PHP you can reference it with $_SERVER['BASE_PATH']

sushil bharwani

Try this:

$_SERVER['DOCUMENT_ROOT']
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!