Does PHP include_path use working directory as fallback?

Viewed 65

I have a PHP script executed via php /dir2/main.php while on /dir1 as a working directory. They both have identical file and the include_path is set to /dir2 however if the file is missing I would expect require('file') to throw an error but instead /dir1/file is loaded even though it's not in the include_path

var_dump(get_include_path()) => string(5) "/dir2"

It seems that the working directory is used as fallback but I couldn't find any mention in the documentation.

Edit: Here's a representation of the directory structure and the code used.

/dir1
    file.txt (I am 1)
/dir2
    file.txt (I am 2)
    main.php

main.php

<?php
set_include_path(__DIR__);
require('file.txt');

bash:

> cd /dir1
> php /dir2/main.php
> rm /dir2/file.txt
> php /dir2/main.php

output:

I am 2
I am 1
1 Answers

This is expected behavior. From the include() documentation:

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. The include construct will emit an E_WARNING if it cannot find a file; this is different behavior from require, which will emit an E_ERROR.

And as noted, include and require are identical in how they look up files, and only differ in how they react if a file is not found.

Related