PHP: How to find server path of current file

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Sometimes you need to find the absolute server path of the current file in order to determine the root location of your PHP application.  Provided that your current file is at the root of your application, you can put …

<?php
echo dirname(__FILE__);
?>

This will then tell you the absolute server path of the current file (which happens to be the absolute server path to the root of your application).  You might even want to save this into a session variable, then file everywhere else in your application can access it and build absolute paths to various sub-directories within the application.

__FILE__ is a “magic constant” that returns…

“The full path and filename of the file. …  __FILE__ always contains an absolute path with symlinks resolved” (from PHP.net)

Then dirname will strip off the filename and give you the absolute path that the file is in).  It returns the path without the trailing slash.  PHP.net says …

“the returned string is path with any trailing /component removed.”

If you are testing this file out on your live server, remember to delete it.  It is a security risk to echo out the server path out.  The above is just for educational purposes and not for production code.