Paths

Code Run Directly From This Page

Two lines of PHP code are run here. Each line of code is shown and followed by the output from running it:


  echo "<p>".__DIR__."</p>";
    

/var/www/stevespages.org.uk/public_html/code-examples/paths

and:


  echo "<p>".$_SERVER['DOCUMENT_ROOT']."</p>";
    

/var/www/stevespages.org.uk/public_html

Same Code Run From File Included From inc/

The same two lines of code were put in a file which was put in a directory called inc. So, the tree diagram of directories and files is:


  paths/
  ├── inc
  │   └── file.php
  └── index.php // this file rendering in the browser
    

Beneath this line the following PHP statement occurs: require 'inc/file.php'

/var/www/stevespages.org.uk/public_html/code-examples/paths/inc



/var/www/stevespages.org.uk/public_html

__DIR__ versus $_SERVER['DOCUMENT_ROOT']

The value of __DIR__ from the echo __DIR__; statement directly written in this, index.php, file is different from the value of the same statement executed by running this, index.php, file but included from a different file at run time. The value of __DIR__ is the path to the file that contains it. That value is not changed at run time even if the contents of that file are executed after being included by another file in a different directory.

The value of $_SERVER['DOCUMENT_ROOT'] is going to be the same wherever it is written or executed on the server. It can also create an absolute path for a file and so could be used to link.

Conclusion

The main conclusion is that I am confused. Secondly, I think both __DIR__ and $_SERVER['DOCUMENT_ROOT'] can be used in the particular case where a file is included which includes another file. However in the case where you have a lot of file in different directories all linking to the same main.css file you could not use __DIR__ in any useful way as far as I can see. However you could use $_SERVER['DOCUMENT_ROOT'] plus the relative path from that root to main.css. Then your link to main.css would be the same for every file and would be less effort to write and maintain.

It seems $_SERVER['DOCUMENT_ROOT'] is more generally useful and if you are going to use it you might as well use it exclusively and forget about __DIR__. Another point is that although __DIR__ combined with the relative path to the resource does result in an absolute path, it is not necessarily a straightforward path to the resource from the document root. The path goes from the root to the file that includes the resource and then from there to the resource. That might mean the path back tracks on itself (using one or more ../). To me this is less than great.

There is a detailed look at using __DIR__ for a case where a file includes a file which includes a file which may be worth looking at.