简体   繁体   中英

PHP how to use relative paths if chained includes

I have the following file system:

-dir1
    -dir2
        -a.php
    -dir3
        -b.php
    -index.php
-dir4
    -dir2
        a.php
    -index2.php

The two a.php files are not the same!

dir1/dir3/b.php includes dir1/dir2/a.php (within a function). Now both index.php and index2.php must be able to include b.php correctly, that is, it should always be dir1/dir2/a.php that is includes, never dir4/dir2/a.php.

I can not delete or rename dir4/dir2/a.php, because the system I'm working on is big, badly structured and I will most certainly break something.

I don't know what relative path to use in b.php for accessing the correct a.php, if I want it to work for both index.php and index2.php. Can anyone suggest something? dirname(__FILE__) doesn't work since I need to go out from dir3 to get into dir2.

This is in fact simplifying my problem - I want to be able to access b.php from ANYWHERE in my system, and be sure that it is always dir1/dir2/a.php that is called from here, even if there is another file dir2/a.php relative to where I'm including b.php from.

You can use .. as reference to parent folder

So if you file is in ./a/b/c/d and you want to reach file in /a/b/e/f you need to use

require_once( __DIR__ . '/../../e/f/second_file.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