Home  >  Article  >  Backend Development  >  The difference between relative paths and absolute paths in php

The difference between relative paths and absolute paths in php

王林
王林Original
2019-09-17 13:04:343986browse

The difference between relative paths and absolute paths in php

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 &#39;./c/d.php&#39;

b.php

<?php
 
    define(&#39;__B&#39;, &#39;this is a test&#39;);

c/d .php

<?php
 
    include &#39;../b.php&#39;;
 
    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__.&#39;/../b.php&#39;;
    var_dump(__B);

b. php

<?php
 
    define(&#39;__B&#39;, &#39;this is a test&#39;);

c/d.php

<?php
 
    define(&#39;__B&#39;, &#39;this is a test&#39;);

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn