Search code examples
phpincluderequireinclude-path

Need help with PHP "include" - How to save the path to my website in variable?


I use the following scheme to include PHP files:

require($_SERVER['DOCUMENT_ROOT'] . "Path/To/My/Website/Path/To/My/File.php");

I would like to save

$_SERVER['DOCUMENT_ROOT'] . 'Path/To/My/Website'

in some variable, say $my_website, and write:

require("$my_website/Path/To/My/File.php");

This way, if I decide to change the path to my website, I will need to modify it only in one place in my code.

Some PHP files may be included several times and from different directory levels. For example:

$_SERVER['DOCUMENT_ROOT']
                         Path
                             To
                               My
                                 Website
                                        Dir1
                                            a.php
                                        Dir2
                                            b.php that includes a.php
                                        Dir3
                                            Dir4
                                                c.php that includes a.php

However, I can't think how to do this.

Please suggest.


Solution

  • Use include path - will make your life simpler (you can control it even from .htaccess).