Search code examples
phpincludeapache2include-path

PHP include path problem


I have set apache so that all requests go to a file /var/www/common_index.php

Now, common_index.php looks at requested file name and sources appropriate file /var/www/123/public_html/requested_file.php

I am having problems when I include a file (with relative path) in requested_file.php. It tries to search for file in /var/www instead of /var/www/123/public_html/

How to solve this?


Solution

  • You can change the working directory in requested_file.php before calling include to make it work:

    chdir(dirname(__FILE__));
    include 'path/to/file.php';
    

    or for PHP 5.3+

    chdir(__DIR__);
    include 'path/to/file.php';
    

    If you don't want to change the working directory (which will affect other file system operations) then just append the path each time you do an include using the magic constant __DIR__:

    include dirname(__FILE__) . '/path/to/file.php';
    include __DIR__ . '/path/to/file.php'; # for PHP 5.3+
    

    where the path is relative to the file where you used the code above.