后端和前端的站点根目录

Let's say that I have this website file root structure:

  • frontend /home/username/public_html/
  • backend /home/username/public_html/admin/

In frontend folder there is a file called config.php. In this file I get the site root of my website like this:

define('ROOT', dirname(__FILE__));

This file is also included in both index files (index.php) in frontend and backend. But for backend, the root is /home/username/public_html/admin/, which should actually be /home/username/public_html/. How can I do this, in one line, in config.php?

LE:

Demo code http://pastebin.com/LGrrJzaV

The FILE gives you the full path and filename of the file.

The dirname() returns the path of the parent directory.

So, if you use:

define('ROOT', dirname(__FILE__));

It gives you the directory structure for the location of the current script.

To be inside the admin/ and have returned the previous folder:

$path = dirname(__FILE__);

define("ROOT", $path.'/../');

// Outputs:  /home/username/public_html/

In one line being inside admin/:

define("ROOT", dirname(__FILE__).'/../');

EDITED

Have the same path for both locations in one line:

define("ROOT", (strpos(dirname(__FILE__), "admin")>=0) ? (str_replace("admin", "", dirname(__FILE__))) : (dirname(__FILE__)));

This will output on both index.php:

  • frontend /home/username/public_html/ -> /home/username/public_html
  • backend /home/username/public_html/admin/ -> /home/username/public_html

You could use

define('ROOT', $_SERVER['DOCUMENT_ROOT']);