phpincluderequireinclude-pathserver-side-includes

Change of folder path when require/ include an php file


I am currently using an index.php to include another file , it structure like:

root / index.php
     / new/ index.php
          / img/ test.jpg

And I write following in root/index.php :

<?php
require_once("new/index.php");
?>

the problem is , all paths in it are wrong. As all paths are based on new/index.php.

For example, In new/index.php my test.jpg is like

<img src="img/test.jpg" />

It shows http://www.test.com/new/img/test.jpg when I directly access new/index.php

But it shows http://www.test.com/img/test.jpg when I include the php in index.php.

How to fix it? I tried chdir() but it does not work expect Thanks


Solution

  • Make sure you always include with an absolute path, like:

    require_once(dirname(__FILE__) . "/otherfile.php");
    require_once(dirname(__FILE__) . "/../uponefolder.php");
    require_once(dirname(__FILE__) . "/sub/folder/file.php");
    

    Or use autoloading.