PHP中的错误处理

PHP中的include包含路径问题

喜洋洋 posted @ 2012年4月24日 15:36 in PHP , 1527 阅读

在C语言和其他语言中include某个文件一般是以包含文件的该文件所在目录为当前目录,但是php则不然,它是以顶层的php文件所在的目录为当前目录,即a包含b,b如果包含c,此时b的当前目录为a所在目录,不是b所在目录。

首先我们来看php官方手册中对include的文件搜索原则的描述:

Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries , current working directory is /www/ , you includedinclude/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/ . If filename begins with ./ or ../ , it is looked only in the current working directory.

寻找包含文件的顺序先是在当前工作目录的相对的 include_path 下寻找,然后是当前运行脚本所在目录相对的 include_path 下寻找。例如 include_path 是 . ,当前工作目录是 /www/ ,脚本中要 include 一个 include/a.php 并且在该文件中有一句 include "b.php" ,则寻找 b.php 的顺序先是 /www/ ,然后是 /www/include/ 。如果文件名以 ./ 或者 ../ 开始,则只在当前工作目录相对的 include_path 下寻找。

和C语言一样php可以设置包含路径,set_include_path(), get_include_path();

下面给出一个例子,来说明php的include的使用。

a.php

<?php 

echo "current directory".getcwd()."</br>";
echo get_include_path()."</br>";
include ("include/c.php");
?>

include/c.php

<?php

echo "this is file: Include/c.php</br>";
echo "this file gcwd:".getcwd()."</br>";

include ("d.php");

?>

include/d.php

<?php

echo "this file include/d.php</br>";

echo "current directory:".getcwd()."</br>";


?>

d.php

<?php

echo "this top d.php</br>";

?>

如果d.php 和include/d.php 同时存在,

运行a.php,当前目录为网站根目录,a包含c,根据查找规则,当前目录相对的include_path优先,则查找到c。

c包含d.php文件,同样的当前目录优先,但注意此时的当前目录为a所在的目录,故查找到的d文件,为根目录下的d.php文件,如果根目录下的d文件不存在,才会查找c文件所在的目录的include_path,此时才会包含include/d.php文件。

运行效果如下:

current directory/var/www/test
.:/usr/share/php:/usr/share/pear
this is file: Include/c.php
this file gcwd:/var/www/test
this top d.php

如果根目录下的d文件不存在:

current directory/var/www/test
.:/usr/share/php:/usr/share/pear
this is file: Include/c.php
this file gcwd:/var/www/test
this file include/d.php
current directory:/var/www/test

Avatar_small
celebrity heights 说:
2022年1月25日 00:02

If you are curious about heights of celebrities, here's a database on celeb height wiki for you to find all the information you need.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter