Search code examples
phpinclude-pathrequire-onceset-include-path

php require_once includes files relative to file instead of working directory


I have some problems with including files relatively. The problem isn't that require_once can't find a file, but the fact that it CAN find a file in a place where the file isn't. I have stripped down the problem to three small classes.

So this is my dir structure:

public_html/
    index.php
    commands/
        CommandFactory.php
        account/
            Status.php

index.php:

require_once 'commands/CommandFactory.php';

$factory = new CommandFactory();

CommandFactory.php:

    class CommandFactory{

    public function __construct()
    {
        echo getcwd() . '<br/>'; //xxx\public_html (which is good, this is where index.php is
        //require_once 'account/Status.php'; // This works as expected
        require_once 'account/Status.php'; // This ALSO works, but it shouldn't

        $status = new Status(); // This works, though it shouldn't. 
    }
}

I have tested by moving the CommandFactory to a different dir, which solves the problem. However, I cannot understand why the file can be included. It shouldn't include Status, relative from the CommandFactory, it should be relative from index.php. I added the current working dir, to see what goes wrong, but i can't figure it out. Anybody knows how and why this works?


Solution

  • From the php.net site :

    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 a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error

    source