Fork me on GitHub

article

Setting the base directory in PHP

September 30, 2006 | Web Design & Development

Knowing the base directory that you’re working from when building a site is a pretty basic need. For the longest time I had been content with just manually setting the base paths and switching between them based on the name of the server.

I recently learned a much better way. I hadn’t really sought this out since I really hadn’t thought about a better way to do it since my old way worked. This new way takes away the need to manually define your document root.

A very handy thing to do is have a constants file that holds all your commonly used information and most of the time this file is in or near your document root. A single line of PHP helps us find where this file is and use it to set the document root for the site.

define('DOCUMENT_ROOT', dirname(realpath(__FILE__)).'/');

That snippet of code will define a document root (including the trailing slash) constant that can be called from any script.

__FILE__ is a magic constant that contains the full path to the file it is written in. No matter if this file is included within another one, it always points to the file in which it was written. Since older versions of PHP would sometimes return a relative path to the file we need to call realpath() on the string. We shouldn’t need to do that now in newer versions of PHP but for safety’s sake I keep it in. Finally dirname() returns just the directory in which the file is contained and negates the need to manually remove the filename from the path.

Its pretty easy to adjust this snippet to adjust for where the constants file is stored. With this you’ll never need to worry about where your site is hosted and what the base path is as it’ll automatically know where its document root is.

6 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  • Quite the handy tip, especially for those who wouldn’t have thought to do that.

    Joey Brooks, October 2, 2006 12:26 am | permalink

  • Thanks, really helpful stuff. I appreciate the information my friend.

    Erik, July 9, 2011 1:40 pm | permalink

  • Thanks – this will make coding on my local machine so much easier!!! Now just to work with ini_set() so I can finally stop using relative pathing…

    Phil Denton, September 25, 2011 11:11 pm | permalink

  • Hey, thank you, very very good!!! I Like this.

    Pyetro SaFe, July 3, 2012 1:09 pm | permalink

  • Snippets like this are always useful

    Peter Fisher, October 6, 2012 4:27 am | permalink

  • THANK YOU!!!! YOU SAVED ME FROM FURTHER TRAUMA!

    sharrikul, February 3, 2014 8:13 am | permalink

Comments are closed