PHP中include路径的解决方法汇总
这几天整理一份很乱的代码,这才意识到php对include处理不是一般的贱:别的编程语言在处理include中的相对目录时,都是以当前处理的文件作为基准。也就是说,如果A包含B,B包含C时,C再包含一个含相对路径的文件,那么路径是相对于C的。这样的处理很自然,符合人们的直觉,也便于开发出路径无关的程序包。
可是PHP不这样,它优先相对工作目录来处理,并且如果路径中包含. ..的话,则只相对于工作目录。
也许PHP这样处理有它的理由,有谁知道的不妨告诉我。
下面是解决这一问题的几种方式:
- __FILE__
__FILE__ always equals to the real path of a php script regardless whether it''s included.
__FILE__ helps you specify the file to include using relative path to the including file.
这种方法首选推荐。虽然你的include语句会因此要写得长一些,但是一个字,值!
本文来自:http://www.87717.com
include dirname(__FILE__).''/subdir'';
//dirname return value does not contain the trailing slash
?>
- $_SERVER[''DOCUMENT_ROOT'']
This method allows you to specify a path relative to the web server doc_root for file inclusion.
这也是许多项目在采用的一种不错的方式,就我看来,缺点是,整个项目不方便移动。
例如你一开始放置在xxx.com/,后来需要放到xxx.com/abc/下的话,你要改文件(在一个公有文件中计算ROOT的位置,其他文件包含这个共有文件)。
特别是当你同一份代码放多处时(例如一个测试环境和一个正式环境),你改文件也不好改。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

In this chapter, we are going to learn the following topics related to routing ?

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Validator can be created by adding the following two lines in the controller.

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.
