简体   繁体   中英

Change working directory

Sorry for asking again, but I really need help. 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?

Some body suggested to use these:

$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

However, even i can see the current url is root directory after chdir(), it still includes this root/blog/lib......

The path to the file you need depends on were you are calling the file. Examples:

In /root calling file in /root -> include_once('header.php');
In /root calling file in /root/lib -> include_once('lib/header.php');
In /root/lib calling file in /root -> include_once('../header.php');
In /root/blog calling file in /root/lib -> include_once(../lib/'header.php');
In /root/blog/css calling file in /root/lib -> include_once(../../lib/'header.php');

If you do like this all path are relative and you can change the root folder and everything still works.

Another option is you have a file called "common.php" or "include.php" were you define path for some folders. This is useful if your site directory has many sub folders.

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