[英]Included file from a parent folder that includes a file from another folder
标题很难理解,但我的问题很简单:
我有:
config.php
include('config_mysql.php');
include('language/english.php');
然后我有: index.php
include('config.php');
然后: /ajax/ajax_vote.php
include('../config.php');
为什么index.php
包含config_mysql.php
和language/english.php
但ajax/ajax_vote.php
仅包含config_mysql.php
?
对于基本文件夹include()
是永诺原始脚本的基础文件夹,因此include()
秒的内部include()
d脚本将是非直观的:
ajax/ajax_vote.php
将(尝试)包括
ajax/../config.php
-> ajax/sonfig_mysql.php
ajax/language/english.php
您可能想看看
$BASEDIR=dirname(__FILE__);
include("$BASEDIR/config_mysql.php");
include("$BASEDIR/language/english.php");
和朋友。
原因是language/english.php
与config.php
不在同一目录中。 另外,/ /ajax/ajax_vote.php
在根文件夹之外。
但是,PHP仍设法正确地包含文件。 我不明白为什么/ajax/ajax_vote.php
不包含文件language/english.php
。 如果我误解了这个问题,请纠正我。
Eugen所说的是正确的,这是因为基本路径与所包含的脚本不同。
同样从我的测试(因为我遇到了类似的问题)看来,php include()在包含文件时将存储另一个临时的include_path,这就是为什么ajax_vote.php可以包含config_mysql.php的原因。 为了说服自己,请尝试将config_mysql.php移到您的ajax文件夹中:它会以相同的方式工作,并且config.php将能够包含它(但仅当执行ajax_vote.php时,而不是index.php!)。 在这种情况下,您有两个包含路径:“ / ajax /”和“ /”。
但是,当您使用路径(不仅包括要包含的文件名,还指定字符串中的文件夹)时,包含路径仅基于执行脚本(例如:仅'/ ajax /')。
您可以通过以下方法解决此问题:
include(dirname(__FILE__).'/language/english.php'); // don't forget the prepended '/'
要不就:
include('/language/english.php'); // here again the prepended '/'
但是,我警告您,我尚不完全了解为什么第二种方法行得通,将第一种方法与dirname()一起使用可能会更安全。
/ EDIT:我刚刚发现include('/ path / to / file')在Windows操作系统上可能是一个错误:在Windows上它等于dirname(__ FILE__),但是在UNIX上它等于根路径。 因此dirname(__ FILE__)绝对更可靠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.