One of Those Noob PHP Issues That Is Easier to Resolve Than You Think
It’s well after midnight, and it’s time to go to bed. We’ve put a new site online today, making for a total of three websites deployed in the past week. So, this wonderful little PHP issue comes up rather frequently because it’s a common bug we create, that we then have to fix.
We are not infallible.
The issue at hand is that old programming trick used in PHP code, that designed to call images or address links or link external files. It’s the old $_SERVER[‘WHAT_GOES_HERE’] issue. In some cases you’ll call ‘SITE_ROOT’, and in other cases it’s ‘DOCUMENT_ROOT’. But when, exactly, does one use one or the other in one’s code?
Excellent question, and here’s the very simple answer: When linking a file, such as ANY include file, you would use the ‘DOCUMENT_ROOT’, because you are attaching a file that is relative to the document’s root directory.
Ergo, <?php include ($_SERVER[‘DOCUMENT_ROOT’].”/includefile.php”); ?>. Simple enough, right? Good.
However, if you are grabbing an image, or perhaps importing a file inside an “echo” statement, you must reference the ‘SITE_ROOT’, as this looks for the absolute path for the website, then crawls through the directory structure. Essentially, ‘DOCUMENT_ROOT’ is for code, and ‘SITE_ROOT’ is for HTML.
E.g.: <?php echo “<img src='”.$_SERVER[‘SITE_ROOT’].”/images/mypic.jpg”‘ border=’0’>”; ?>
Of course, there is also the $_SERVER[‘PHP_SELF’] global, which is usually used when sending and receiving form data in redux, but that’s another issue, entirely. Have a splendid evening, and feel free to ask questions. I may know an answer, here and there!