[英]require/require_once “../” breaks loading of page without throwing error
工作目录:
rootDir
dir1
file1.php
dir2
file2.php
main.php
main需要file1,file1需要file2。 Main可以要求file1没有问题。 但是file1不需要file2。 我的初始尝试要求file2(在file1中):
require_once '../dir2/file2.php';
当我访问main.php时,我只会得到一个白页,没有任何内容发送到客户端。 所以我尝试捕获一个异常:
try {
require_once '../dir2/file2.php';
echo "Succesfully required file";
} catch (Exception $e) {
echo $e->getMessage();
}
这也导致白屏。 没有错误消息显示,没有写回显。 我发现需要file2的唯一方法:
$root = realpath($_SERVER['DOCUMENT_ROOT']);
require_once "{$root}/rootDir/dir2/file2.php";
为什么“ ../”不起作用?
编辑:
更好的解决方案是(谢谢:@Ulrich Eckhardt和@Paulpro)
require_once __DIR__ . '/../dir2/file2.php';
我个人不希望相对路径以任何特定方式起作用。 问题是,传统上(即在大多数OS功能中),路径是相对于进程的当前工作目录(CWD)解释的,但在这里您可能希望它相对于当前文件的目录起作用。 不要使用相对路径,而是要明确使用__DIR__
来指定当前文件的目录:
require_once __DIR__ . '/../dir2/file2.php';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.