问题
I created a php project like this:
- img
- js
- php
- config
- config.php
- pages
- news.php
- contact.php
- config
I need to include my config.php
into all my files news.php
, contact.php
How to avoid to have a relative path like ../config/config
?
I would like to have a root path like php/config/config.php
.
I use MAMP Pro. Should I use an environment variable to save the root path?
回答1:
In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:
$_SERVER['DOCUMENT_ROOT']
The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.
回答2:
Make a folder in your root. Name it e.g. Helpers/
. Make a file in it path.php
and inside it put this code.
function base_path($path = "") {
return realpath(__DIR__ . '/../') . DIRECTORY_SEPARATOR . $path;
}
then include this file at the top of your every web document same as you do for your session start and then you can use this function any where in your code. Like so
<?php
require "Helpers/path.php";
require base_path('php/config/config.php');
回答3:
Create a constant with absolute path to the root by using define in ShowInfo.php:
define('ROOTPATH', DIR); OR (PHP <= 5.3)
define('ROOTPATH', dirname(FILE));
回答4:
1 Find out your document root. This value is the same for all your scripts
echo $_SERVER['DOCUMENT_ROOT']; exit;
2 Use the path relative to the document root whenever you include config.php
(adjust the line below once you know your document root)
require_once $_SERVER['DOCUMENT_ROOT'].'/php/config/config.php';
来源:https://stackoverflow.com/questions/38867220/root-path-variable-in-a-php-project