search
HomeBackend DevelopmentPHP TutorialPHP: require and include path issues

PHP: require and include path issues

Jun 25, 2017 am 10:35 AM
includephprequirepathquestion

FILE is a preprocessed variable, processed before running, and has been replaced before the file is included.
The content of the file required include is processed at runtime, and its code is run in the space of the included file, a relative path, relative to the included file.

1 Absolute path, relative path and undetermined path

Relative path

Relative path refers to the path starting with ., such as

./a/ a.php (relative to the current directory)
../common.inc.php (relative to the upper-level directory),

absolute path

The absolute path starts with / or windows C:/ similar to the path starting with the drive letter, the full path can uniquely determine the final address of the file without any reference path. For example

/apache/wwwroot/site/a/a.php
c:/wwwroot/site/a/a.php

Undetermined path

Any path that does not start with . or /, nor does it start with the Windows drive letter:/, such as

a/a.php
common.inc.php,

At first I thought this was also a relative path, but in PHP's include/require inclusion mechanism, this type of path is handled completely differently from relative paths starting with . require './a.php' and require 'a.php' are different!

Let’s analyze the processing methods of these three types of include paths: First, remember a conclusion: if the include path is a relative path or an absolute path, it will not go to include_path (the include_path environment variable defined in php.ini, Or use set_include_path(...) to find the file in the program.

Test environment description

Note: The following discussion and conclusion are based on this environment: Assume A=http://www.xxx.com/app/test/a.php, emphasize again The following discussion is for the case of direct access to A.

2. Relative path:

The relative path requires a reference directory to determine the final path of the file. In include parsing, no matter how many levels of nesting are included, this reference directory is the program execution Entry file directory.

Example 1

A defines require './b/b.php'; // then B=[SITE]/app/test/b/b.php
B Definition require './c.php'; // Then C=[SITE]/app/test/c.php is not [SITE]/app/test/b/c.php

Example 2

A defines require './b/b.php'; // Then B=[SITE]/app/test/b/b.php
B defines require '.. /c.php'; // Then C=[SITE]/app/c.php is not [SITE]/app/test/c.php

Example 3

A defines require '../b.php'; //then B=[SITE]/app/b.php
B defines require '../c.php'; //then C= [SITE]/app/c.php is not [SITE]/c.php

Example 4:

A defines require '../b.php' ; // Then B=[SITE]/app/b.php
Define require './c/c.php' in B; // Then C=[SITE]/app/test/c/c.php Not [SITE]/app/c/c.php

As defined in Example 5

A require '../inc/b.php'; // then B=[SITE]/app/inc/b.php
B requires require './c/c.php'; // Then C still =[SITE]/app/test/c/c.php No [SITE]/app/inc/c/c.php

Example 6

A defines require '../inc/b.php'; // Then B=[SITE]/app/inc/b.php
B requires require './c.php'; // Then C=[SITE]/app/test/c.php is not [SITE]/ app/inc/c.php

3. Absolute path

The absolute path is relatively simple and not easy to cause confusion and errors. require|inclue corresponds to the file on the disk. .

require '/wwwroot/xxx.com/app/test/b.php'; // In Linux
require 'c:/wwwroot/xxx.com/app/test/b.php' ; // In windows,

dirname(FILE) is also calculated as a directory in the form of an absolute path, but please note that FILE is a Magic constants, which is equal to The absolute path of the PHP file where this statement is written. Therefore, dirname(FILE) always points to the absolute path of the PHP file where this statement is written. It has nothing to do with whether this file is included and used by other files.

Example 1

A defines require '../b.php'; FILE).'/c.php'; // Then B=[SITE]/app/c.php

Example 2

Define require '../inc/b.php'; in A php'; // Then B=[SITE]/app/inc/c.php is always in the same directory as B

Conclusion: No matter whether B is included and used by A, or directly accessed

Bif require dirname(FILE).'/c.php'; // always refers to the c.php file in the same directory as B;

Bif require dirname(FILE). '/../c.php'; // Always reference the c.php file in the parent directory of the directory where the B file is located;
BIf require dirname(FILE).'/c/c.php'; // Then always refer to the c.php file in the c subdirectory of the directory where the B file is located;

4. Undetermined path

First use the includes defined in include_path one by one Directory to splice [undetermined path]. If an existing file is found, it will include successful exit. If it is not found, use the directory where the php file that executes the require statement is located to splice the full path composed of [undetermined path] to find the file. If the file If it exists, it means successful exit, otherwise it means the included file does not exist and an error occurs. Undetermined paths are easy to confuse and are not recommended.

5. Solution

Since the "reference directory" in "relative path" is the directory where the execution entry file is located, the "undetermined" path is also easier to confuse, so the best solution is It is to use the "absolute path"; for example, the content of b.php is as follows. No matter where b.php is required, the path of b.php is used as a reference to require c.php

$dir = dirname(FILE );

require($dir . '../c.php');

Or define a general function import.php, set it to "automatically import files in advance", in Make the following configuration in php.ini

Change the configuration item (required) auto_prepend_file = "C:\xampp\htdocs\auto_prepend_file.php"

Change the configuration item (optional) allow_url_include = On

The content of import.php is as follows

function import($path) {    
    $old_dir = getcwd();        // 保存原“参照目录”
    chdir(dirname(FILE));    // 将“参照目录”更改为当前脚本的绝对路径
    require_once($path);
    chdir($old_dir);            // 改回原“参照目录”
}

In this way, you can use the import() function to require the file. No matter how many levels of "reference directories" it contains, it is the current file

The above is the detailed content of PHP: require and include path issues. 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
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function