Why does this PHP relative include fail?

前端 未结 2 693
遥遥无期
遥遥无期 2021-01-20 05:03
disc@puff:~/php$ ls 
a.php  data  include 

disc@puff:~/php$ tree 
. 
├── a.php 
├── data 
│   └── d.php 
└── include 
    ├── b.php 
    └── c.php 
2 directories, 4         


        
相关标签:
2条回答
  • 2021-01-20 05:27

    paths are always relative to the script which got called. in your example c.php is loaded because "." (current directory) is always in the include_path.

    to fix this you can use dirname(__FILE__) to always know the directory of the file itself. (the file in which you write FILE)

    or you can use dirname($_SERVER['SCRIPT_FILENAME']) to alwys get the directory of the caling script.

    0 讨论(0)
  • 2021-01-20 05:41

    As you're starting with a.php, you should define the include directories in a.php:

    define('MY_INCLUDES', dirname(__FILE__) . '/include/');
    define('MY_DATA', dirname(__FILE__) . '/data/');
    

    Afterwards include the files with absolute paths:

    include(MY_INCLUDES . 'b.php');
    include(MY_DATA . 'c.php');
    
    0 讨论(0)
提交回复
热议问题