First of all, let’s take a look at the directory structure of our example and the contents of these three files.
a.php
<?php include './c/d.php'
b.php
<?php define('__B', 'this is a test');
c/d .php
<?php include '../b.php'; var_dump(__B);
The d.php file under the c directory refers to the b.php file under its parent directory. When running c/d.php alone, no error will occur. Problem, however, if a.php in the same directory as b references c/d.php, there will be a problem, and it will report an error saying that the file does not exist.
Thinking:
It probably means that after a.php introduces c/d.php into a.php, include '../b. The path php' is relative to a.php, and the relative path to a.php does not exist, so this problem occurs. It is quite easy to cause problems when using relative paths when a file may be referenced in multiple places, and then we can easily solve this problem by using absolute paths.
Use absolute paths to solve the problem
a.php
<?php include __DIR__.'/../b.php'; var_dump(__B);
b. php
<?php define('__B', 'this is a test');
c/d.php
<?php define('__B', 'this is a test');
In this way, the absolute path of the file is referenced, __DIR__
is a predefined magic constant that has been available since php5.3, indicating the directory where this file is located. Then we can use this to write the absolute path when running a.php and c/d.php It can be executed normally. If before php5.3, dirname(__FILE__)
was used instead of __DIR___
.
Summary: In php, the absolute path refers to the absolute location in the directory, which directly reaches the target location, usually the path starting from the drive letter; the relative path is based on a reference. Find the file you need i.e. the relative path is relative to the target directory.
The above content is for reference only!
Recommended tutorial: PHP video tutorial
The above is the detailed content of The difference between relative paths and absolute paths in php. For more information, please follow other related articles on the PHP Chinese website!