问题
I have a problem tring to use require_once. I am specifying a wrong path and I can't find a solution.
I have a file named header.php that includes two files by using require_once: functions.php and navigation.php. This part is working fine. The problem appears when I try to include header.php in a file named view.php located in a different directory.
here is the arborescence:
C:\wamp\www\1.1\plugins\docreader\php\view.php
C:\wamp\www\1.1\theme\dark-blue\templates\files\header.inc.php
C:\wamp\www\1.1\theme\dark-blue\templates\files\functions.inc.php
C:\wamp\www\1.1\theme\dark-blue\templates\files\navigation.inc.php
I tried a lot of different paths but without any success.
Do someone have a clue please ?
回答1:
Read about (and use) the magic constant __DIR__ and function dirname() to generate the path of the included file starting from the path of the includer.
For example, if in plugins\docreader\php\view.php
you want to include theme\dark-blue\templates\files\functions.inc.php
then use something like this:
// Use this in 'plugins\docreader\php\view.php'
include dirname(dirname(dirname(__DIR__))).
'/theme/dark-blue/templates/files/functions.inc.php';
__DIR__
is a magic constant that evaluates to the directory that contains the file where it is used. In C:\wamp\www\1.1\plugins\docreader\php\view.php
, the value of __DIR__
is 'C:\wamp\www\1.1\plugins\docreader\php'
.
The function dirname() returns the parent directory of the provided path. Kind of ..
, only better. Using it three times reduces the value passed as argument (the value of __DIR__
explained above) to 'C:\wamp\www\1.1'
. Everything is straight forward from there: add the relative path to the desired file ('/theme/dark-blue/templates/files/functions.inc.php'
) and forget about inclusion problems.
回答2:
You need to make your file paths absolute rather than relative. A useful super global for achieving this is $_SERVER['DOCUMENT_ROOT']
which will evaluate to your web server file root.
来源:https://stackoverflow.com/questions/29437058/wrong-path-using-require-once