简体   繁体   中英

Using root directories in PHP

When I try to open a file from the site root using / I get this error:

Fatal error: require(): Failed opening required '/templates/header.php' (include_path='.:/usr/local/php70/pear') in /home/cultureh/public_html/staging/index.php on line 3

but when I uses relative directories such as ../ it works fine. Why isn't the root directory method working?

In Linux based OS the / refers to the servers root. Apache and other web hosts typically do not have access to this directory. To get a relative directory simply exclude the leading / and it will be in relationship to the directory the file is in.

For my site since I have files scattered in a 3-4 deep tree structure I use a bootstrap file that I load first on all page loads that has this in it:

DEFINE('ROOT_PATH', dirname(__DIR__)); .

Of course this assumes your bootstrap file is in the site root. You can adjust the constant to go up a directory if you have your bootstrap file in a sub-directory. Then when you want to use a path that is guaranteed to be relative to your site's root simply put: ROOT_PATH . '/templates/header.php' ROOT_PATH . '/templates/header.php' .

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