PHP中include路径修改

1.__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语句会因此要写得长一些,但是一个字,值!

<?php

include dirname(__FILE__).'/subdir';

//dirname return value does not contain the trailing slash

?>
 

2.$_SERVER['DOCUMENT_ROOT']

This method allows you to specify a path relative to the web server doc_root for file inclusion. 
这也是许多项目在采用的一种不错的方式。

<?php

if (!defined("WETSITE_BASE_DIR"))

define("WETSITE_BASE_DIR", $_SERVER['DOCUMENT_ROOT'].'/Clare/');

require_once(WETSITE_BASE_DIR.'includes/global.inc.php');

?>

3.chdir()

The include looks for file relative to current working directory. We can use this feature. It's really a "fancy" way, but I'm not sure whether it's safe all the time. Who knows? 
这种方式感觉稍嫌麻烦了点,随时要记得恢复工作目录也不是容易的事。写完这句话后,我随后写了几个测试文件,发现这种方式的最重要缺点不在麻烦,而在它的副作用:改变了工作目录,这会导致程序逻辑出错。

<?php

$prewd = getcwd(); // get the current working directory

chdir(realpath(dirname(__FILE__))); // change working directory to the location of this file 

include('includedfile.php'); // include relative to this file

chdir($prewd); // change back to previous working dir

?>

4.set_include_path()

这是最方便的方式,但不是没有缺点。首先,有时候你不见得有权限修改配置。其次,当不同路径下的文件名有重复的时候,你会被搞糊涂的(就算你不会,你的维护者呢)。

5.auto_prepend_file and auto_append_file in php.ini 

如果你每个脚本都需要包含一个通用脚本的话,这几乎是最好的方式,但是,缺点还是,与配置相关,不够独立。

原文地址:https://www.cnblogs.com/zhutianpeng/p/4044122.html