Trouble with / vs ./ vs ../ and absolute and relative paths
I have many PHP files in
/
/client/
/user/
/config/
etc...
I want all my files to include /user/codestart.php
. (Lots of functions etc)
Therefore:
- All files in
/
haveinclude("./user/codestart.php");
- All files in
/user/
haveinclude("codestart.php");
- All files in
/client/
haveinclude("../user/codestart.php");
The problem is that /user/codestart.php
has include("../config/config.php");
(The MySQL ID and password)
When a file in /
runs, such as /index.php
, it includes ./user/codestart.php
.
Then /user/codestart.php
includes ../config/config.php
, but it cannot see it, because it thinks it is calling it from /
, instead of from /user/
.
If I change
include("../config/config.php")
to be
include("./config/config.php")
that fixes it for /
files, but breaks it for/user/
and/client/
files.
Bottom line is that when one PHP file includes another f开发者_高级运维ile, PHP thinks it is operating from the location of the original file, not the calling file.
I need to use relative paths, not absolute paths. Absolute paths will not work in my situation.
Is there any way to solve this?
One way to deal with this is this:
Have a central configuration file (e.g.
/myproject/config/bootstrap.php
In that configuration file, define a global root for your application. E.g.
define("APP_ROOT", realpath(dirname(__FILE__)."/.."));
Include that configuration file in every PHP file. E.g.
include("../config/bootstrap.php");
Whenever you reference some other file, use
include APP_ROOT."/includes/somefile.php";
Voilá - you have a fixed point in space (APP_ROOT
) and can reference everything relative to that, no matter which directory you are in.
If you want to do it this way I suggest you make a seperate file for all your includes which is in a fixed dir, the root for example.
Then you reliably include all the files from there using
include __DIR__.'path/relative/from/includefile.php'
If your php verion is lower than 5.3 you should use dirname(__FILE__)
instead of __DIR__
as mentioned by RiaD
You might like this php.net page
You can use relative paths in conjuntion with dirname(__FILE__
)
So in your codestart file write:
require_once dirname(__FILE__).'/../config/config.php';
You can set the path that PHP uses to look for files, so that it contains all your folders. In index.php
:
$folders = implode(PATH_SEPARATOR, array('user', 'config'));
set_include_path(get_include_path().PATH_SEPARATOR.$folders);
Then you can just do:
include("codestart.php");
and:
include("config.php");
This will work for index.php
and all files that index.php
includes.
use absolute paths. to get path to your root directory use $_SERVER['DOCUMENT_ROOT']
, ex.
include $_SERVER['DOCUMENT_ROOT'].'/user/codestart.php';
include $_SERVER['DOCUMENT_ROOT'].'/config/config.php';
It save you from absolute paths' problems.
精彩评论