简体   繁体   English

require / require_once“ ../”中断页面加载而不会引发错误

[英]require/require_once “../” breaks loading of page without throwing error

The working directory: 工作目录:

rootDir
    dir1
            file1.php
    dir2
            file2.php
    main.php

main requires file1 and file1 requires file2. main需要file1,file1需要file2。 Main can require file1 without a problem. Main可以要求file1没有问题。 However file1 can't require file2. 但是file1不需要file2。 My inital try at requiring file2 (in file1): 我的初始尝试要求file2(在file1中):

require_once '../dir2/file2.php';

When I visit main.php I only get a white page, nothing gets send to the client. 当我访问main.php时,我只会得到一个白页,没有任何内容发送到客户端。 So I tried catching an exception: 所以我尝试捕获一个异常:

try {
    require_once '../dir2/file2.php';
    echo "Succesfully required file";
} catch (Exception $e) {
    echo $e->getMessage();
}

This, too, leads to a white screen. 这也导致白屏。 No error message is displayed, the echo isn't written. 没有错误消息显示,没有写回显。 The only way I found to require file2: 我发现需要file2的唯一方法:

$root = realpath($_SERVER['DOCUMENT_ROOT']);
require_once "{$root}/rootDir/dir2/file2.php";

Why does '../' not work? 为什么“ ../”不起作用?

Edit: 编辑:

A better solution is (Thanks:@Ulrich Eckhardt and @Paulpro) 更好的解决方案是(谢谢:@Ulrich Eckhardt和@Paulpro)

require_once __DIR__ . '/../dir2/file2.php';

I personally wouldn't expect a relative path to work in any particular way. 我个人不希望相对路径以任何特定方式起作用。 The problem is that traditionally (ie in most OS functions), the path is interpreted relative to the current working directory (CWD) of the process but here you might expect it to work relative to the current file's directory. 问题是,传统上(即在大多数OS功能中),路径是相对于进程的当前工作目录(CWD)解释的,但在这里您可能希望它相对于当前文件的目录起作用。 Instead of using a relative path, be explicit and use __DIR__ to specify the current file's directory: 不要使用相对路径,而是要明确使用__DIR__来指定当前文件的目录:

require_once __DIR__ . '/../dir2/file2.php';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM