Require file including variable
I am currently using the following code to include a file in my webpage:
require_once $_SERVER['DOCUMENT_ROOT'] . '/include/file.php';
However, I have now edited my system so I input the URL into a data file in the root which makes other parts of my site function and allows me to use different directories.
In short, I am using a splash page on a website, where the root is now /directory rather than in the root, thus the URL in my data file is http://www.domain.com/directory.
So, what I need to work out is how to point this line at the directory using the variable from the data file which contains the URL
So $_SERVER['DOCUMENT_ROOT']
becomes irrelevant because I need to grab the data from the variable in the data file which is NOT in the root anymore.
It needs to be something like:
require_once (variable from file a few directories back) + absolute path to file;
I want this 开发者_如何学Pythonline of code to be future-proof too, if I need to build a site using a different directory then the root.
I hope that makes sense!
Create a SITE_ROOT
and use that instead. That way, it will work with any directory change.
define('SITE_BASE', '/directory/');
define('SITE_ROOT', $_SERVER['DOCUMENT_ROOT'] . SITE_BASE);
You can then use SITE_BASE
for creating your URIs:
<a href="<?php echo SITE_BASE ?>subdir/">link</a>
and SITE_ROOT
for accessing files on the system:
require_once SITE_ROOT . 'include/file.php';
Have you considered setting include_path
in your php.ini
file? For instance, my own php.ini
file has include_path = ".:/path/to/web/root"
, which allows me to not worry about where my files are when including them.
In your case, you would want to set it to include_path = ".:/path/to/web/root/directory"
. If you don't know the path to the web root, just run echo $_SERVER['DOCUMENT_ROOT'];
to find it.
This solution is "future-proof", as you only need to change that php.ini
value and everything falls into place.
精彩评论