简体   繁体   中英

include nested php files

I have header.php in the root/lib which is including header_sub.php in the same directory. Normally files in root can directly include them by this code:

include_once('lib/header.php');

but now i have example.php in a sub-directory /blog, if i use these

include_once(../'lib/header.php');  or 
include_once($_SERVER['DOCUMENT_ROOT'].'/lib/header.php');  or 
include_once(dirname(__FILE__).'/lib/header.php');

header_sub.php would not be included correctly.

Is there a way to include header.php and header_sub.php without modifying them?

Change the code in your header file to use absolute paths like you were trying to do with the misc file, use:

include_once($_SERVER['DOCUMENT_ROOT'].'/header_sub.php');

in your header file, this way the include is independent of the current file system location, it's absolute not relative.

Ok, found another solution that should suit you better that doesn't require you modifying header.php, but rather just whatever file includes the header

<?php 
    $oldcwd = getcwd(); // Save the old working directory
    chdir("../"); // Moves up a folder, so from /blog to /
    include("header.php"); // Include the file with the working directory as if the header file were being loaded directly, from it's folder
    chdir($oldcwd); // Set the working directory back to before
?>

What this does is it changed the working directory for a second, includes the header file (which will all be compiled with the working directory that the header file normally uses), then sets the working directory back to normal for convenience in case you need to include something else later relatively.

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