PHP Include()问题 [英] Php Include() Issues
问题描述
我有三个文件,如下所示
- users.php
- auth.php
- main.php
其中users.php
位于目录/
的根目录. auth和main.php
位于测试文件夹示例/test/auth.php
&中. /test/main.php
.
Users.php
包含以下php代码.
<?php
include('test/main.php');
?>
auth.php
包含以下php代码.
<?php
include('../test/main.php');
?>
main.php代码
<?php
include('test/db.php');
?>
在我执行users.php
的地方,它运行正常,但是当我执行位于根文件夹中的users.php
时,输出却很完美,但是如果我正在执行/test/auth.php
Warning: include(test/db.php) [function.include]: failed to open stream: No such file or directory in /path/db.php on line 2
有没有解决方法以正确的功能访问auth.php
错误.
包含项始终相对于工作目录(实际上,相对于 PATH 而言,工作目录是一部分).工作目录由正在执行的脚本确定.假设您具有以下结构:
webroot/
foo.php
folder/
bar.php
通过命令行上的$ php foo.php
或通过在浏览器中访问localhost/foo.php
运行foo.php
时,工作目录为webroot/
.如果运行folder/bar.php
,则工作目录为webroot/folder
.
要确保您包含的文件相对于文件 include
所在的位置,请使用以下命令:
include __DIR__ . '/folder/bar.php`;
那个,或者更改您的PATH 以添加您的项目根目录,并且始终包含相对于项目根目录的目录.我更喜欢上面显示的相对文件,或者自动加载.>
I am having three files which are as follows
- users.php
- auth.php
- main.php
where users.php
is located at root of the directory /
. auth and main.php
is located into the test folder example /test/auth.php
& /test/main.php
.
Users.php
containing following php code.
<?php
include('test/main.php');
?>
auth.php
containing following php code.
<?php
include('../test/main.php');
?>
main.php code
<?php
include('test/db.php');
?>
Where i am executing users.php
it is working perfectly but when i am executing users.php
which is located at root folder gives me output perfect but if i am executing /test/auth.php
Warning: include(test/db.php) [function.include]: failed to open stream: No such file or directory in /path/db.php on line 2
is there any solution to access auth.php
with error with proper function.
Includes are always relative to the working directory (actually, relative to the PATH, of which the working directory is a part). The working directory is determined by the script that's being executed. Say you have this structure:
webroot/
foo.php
folder/
bar.php
When you run foo.php
either through $ php foo.php
on the command line or by visiting localhost/foo.php
in your browser, the working directory is webroot/
. If you run folder/bar.php
, the working directory is webroot/folder
.
To make sure you're including files relative to the file the include
is in, use something like:
include __DIR__ . '/folder/bar.php`;
That, or alter your PATH to add your project root to it and always include relative to the project root. I prefer either file relative includes as shown above or autoloading though.
这篇关于PHP Include()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!