Talk about the relative path problem in PHP and the use of absolute path, php absolute path

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.