Search code examples
phpincludephp-internals

PHP include incorrect search path taken?


I have a file test.php in the folder myfolder. myfolder also contains another folder called inner.

Both myfolder and inner contain a file called msg.php. The entire layout looks like this:

  • myfolder
    • test.php
    • inner
      • msg.php
    • msg.php

In test.php, I've set the include_path to ./inner and included the file msg.php:

<?php
error_reporting(E_ALL | E_STRICT);
ini_set("include_path", "./inner");
echo ini_get('include_path'); // shows ./inner
include("msg.php"); // outputs hello from myfolder/inner/msg.php
?>

However, if I modify the working directory to ./inner, myfolder/msg.php will be included instead of myfolder/inner/msg.php:

<?php
error_reporting(E_ALL | E_STRICT);
ini_set("include_path", "./inner");
echo ini_get('include_path'); // shows ./inner
chdir('./inner');
include("msg.php"); // outputs hello from myfolder/msg.php
?>

Shouldn't the second piece of code include myfolder/inner/msg.php instead of myfolder/msg.php?


Solution

  • Let's first take a look at your directory path syntax.

    ./inner
    

    This is saying, look in the current directory (./) for a directory called inner.

    Before you set the include_path to ./inner, though, you change the current working directory to ./inner, so now you are effectively looking for /myfolder/inner/inner/msg.php.

    Let's take a look at your code again.

    //Current working directory is /myfolder
    
    //Here you change the current working directory to /myfolder/inner
    chdir('./inner');
    
    //Here you set the include_path to the directory inner in the current working directory, or /myfolder/inner/inner
    ini_set("include_path", "./inner");
    
    //You echo out the explicit value of include_path, which, of course, is ./inner
    echo ini_get('include_path'); // shows ./inner
    
    //include fails to find msg.php in /myfolder/inner/inner so it looks in the scripts directory, which is /myfolder/msg.php.
    include("msg.php"); // outputs hello from myfolder/msg.php
    

    Check the documentation which states the following about what happens if include() can't find the file referenced in the provided path:

    include will finally check in the calling script's own directory and the current working directory before failing.

    You should try setting the include_path to /myfolder/inner or, if /myfolder is actually your root, then you could just set it to /inner. Notice the omission of the . which means current working directory. Just using a / means look in the root directory.