Problem description
First, let’s take a look at the directory structure of our example and the contents of these three files.
a.php
<?phpinclude './c/d.php'
b.php
<?phpdefine('__B', 'this is a test');c/d.php
<?phpinclude '../b.php';var_dump(__B);
The d.php file under the c directory refers to the b.php file under its upper directory. It will not have any problems when running c/d.php separately.
However, if a.php references c/d.php in the same directory as b, there will be a problem.
It reports an error saying that the file does not exist
think
The general meaning is that after a.php introduces c/d.php into a.php, the path include '../b.php' is relative to a.php, and the relative path for a.php does not exist, so this problem arises.
If a file may be referenced in multiple places, it is quite easy to have problems, and then we can easily solve this problem using absolute paths.
Use absolute paths to solve the problem
If we change the file to the following
a.php
<?phpinclude __DIR__.'/../b.php';var_dump(__B);
b.php
<?phpdefine('__B', 'this is a test');c/d.php
<?phpinclude __DIR__.'/../b.php';var_dump(__B);
This is changed to referring to the absolute path of the file. __DIR__ is a predefined magic constant that has existed in php5.3, indicating the directory where the file is located. Then we use this to write the absolute path, which can be executed normally when running a.php and c/d.php. If dirname(__FILE__) is used instead of __DIR___ before php5.3
Summarize
The above is all about the problem of relative paths in php and the use of absolute paths. I hope it will be helpful to everyone using PHP and avoid entering the pit of relative paths in php again.