Including relative files with PHP

Consider the following 3 php files in this directory structure:


   ./c.php
   ./1/b.php
   ./1/2/a.php
  

Consider you want to access c.php via the browser, which depends on b.php, which in turn depends on a.php.

Files and their contents are listed below

1/2/a.php


    This is a.php
    <?
      include('../b.php');
    ?>
  
  

1/b.php


    This is b.php
    <?
      include('../c.php');
    ?>
   
  

c.php


    This is c.php
   
  

Now when you access the url 1/2/a.php, the script successfully includes b.php, but not c.php. We received the following warnings


    This is a.php This is b.php
    Warning: main(../c.php): failed to open stream: No such file or directory in /home/www/test/1/b.php on line 3

    Warning: main(../c.php): failed to open stream: No such file or directory in /home/www/test/1/b.php on line 3

    Warning: main(): Failed opening '../c.php' for inclusion (include_path='./:/usr/local/lib/php') in /home/www/test/1/b.php on line 3
  

The problem is that it tries to open '../c.php' relative to the first file, 1/2/a.php, even though the include was made inside b.php.

The solution is to use __FILE__, and dirname to ge the directory of the current php file.

1/b.php should look like


    This is b.php
    <?
      include(dirname(__FILE__).'/../c.php');
    ?>
   
  

Published: Saturday, 4 June 2005