Starting off right with file includes


On my first PHP project, I coded all of my include/require files as:


It’s kind of a pain and not super clear coding in my opinion. Diving into my second PHP project, I was hoping to use the $_SERVER global variable and DOCUMENT_ROOT as below:


Is this better coding practice or might there be another solution that I’m not aware of?

Thank you,


Personally, I much prefer that solution, as you can then use the same link anywhere without having to worry about relative paths.

Thanks so much for the quick reply!



I’ve now given the whole $_SERVER[“DOCUMENT_ROOT”] some thought and now think that there may be one small issue. Let’s say I develop the site for However, it turns out that it needs to be all moved to a subdirectory (this is actually a possibility for the project), so that all of my files now reside in If this does happen, wouldn’t I have to change all of my $_SERVER[“DOCUMENT_ROOT”] to reflect this with the additional layer? And, if this is the case, might there be a more “flexible” solution?

Thanks again…

How about this?

require_once($_SERVER["DOCUMENT_ROOT"] . $SITE_DIR . '/main/restrict_access_index.php');  

Just set a global $SITE_DIR (or whatever name you like) to an empty string. If/when the site moves, simple modify that global variable!


Thank you…

I recently started using constants for this. In my configuration file i declare constants with the right paths. If site moves I change soms constants.
But I don’t know If this is good practise