Talk about the relative path problem in PHP and the use of absolute path, php absolute path
Problem description
First, let's take a look at the directory structure of our example and the content of the 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 references the B. php file under its parent directory to run c/d. php independently.
However, if a. php In the directory at the same level as B references c/d. php, the problem may occur.
The error indicates that the file does not exist.
Thoughts
After a. php introduces c/d. php to a. php,include '../b.php'
This path is relative to a. php, and does not exist for a. php, so this problem occurs.
If a file may be referenced in multiple locations, it is quite easy to use relative paths. Then we can use absolute paths to solve this problem easily.
Use absolute path to solve the problem
If we change the file to the following content:
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);
In this way, the absolute path of the file is referenced, __DIR__
It is a predefined magic constant at the beginning of php5.3, indicating the directory where the file is located. Then, we can use this to write the absolute path and run. php and c/d. php can be executed normally, if it is used before php5.3dirname(__FILE__)
To replace__DIR___
Summary
The above is all about the relative paths in php and the use of absolute paths. I hope it will be helpful for you to use PHP and avoid entering the relative paths in php.