Advantages of Absolute Path in PHP
Using an absolute path is convenient when the file with our script and the file being read are located in subfolders of our site.
Let's look at an example. Suppose we have the following file structure:
- /script/
- index.php
- /directory/
- test.txt
Let's read our file using a relative path:
<?php
echo file_get_contents('../directory/test.txt');
?>
And now let's read our file using an absolute path:
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
echo file_get_contents($root . '/directory/test.txt');
?>
In the second case, even if we move the script file to another location, the path to the file will not need to be changed, because it is set from the root of the site.