The problem of relative path in PHP and the use of absolute path _javascript skill

Source: Internet
Author: User

Problem description

First, 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 in its parent directory and runs c/d.php without problems.

However, if a.php references c/d.php in and B's siblings, there will be problems.

It complains that the file doesn't exist.

Thinking

Presumably the meaning is that a.php the c/d.php into the a.php, include '../b.php' this path is relative to a.php, and then for the a.php of this relative path it does not exist, so there is this problem

If a file may be referenced in more than one place, using a relative path can be quite problematic, and then using the absolute path is an easy way to solve the problem.

Using absolute paths to solve problems

If we change the file to the following content

a.php

<?php
include __dir__. ' /.. /b.php ';
Var_dump (__b);

b.php

<?php
define (' __b ', ' This is a test ');

c/d.php

<?php
include __dir__. ' /.. /b.php ';
Var_dump (__b);

This is changed to the absolute path of the file reference, is the __DIR__ beginning of the php5.3 of the predefined magic constants, indicating the directory where the file, and then we use this to write the absolute path, in the running a.php and D.php can be performed normally if the php5.3 is used dirname(__FILE__) to replace__DIR___

Summarize

The above is about the relative path in PHP and the absolute path of the use of all content, I hope to use PHP can help, to avoid entering PHP in the relative path of the pit.

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.