简体   繁体   中英

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 can require file1 without a problem. However file1 can't require file2. My inital try at requiring file2 (in file1):

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

When I visit main.php I only get a white page, nothing gets send to the client. 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:

$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)

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. Instead of using a relative path, be explicit and use __DIR__ to specify the current file's directory:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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