Find the current directory with PHP

Here is a quick PHP tip that has come in handy for me in times past, it deals with finding the current directory that you are in. I am going to show you how to get two different answers to that question depending on what your needs are. First, let me explain why we would get (or even need for that matter) two different answers. This is because from a PHP page being served up by your web server, there are two current directories from its perspective. One would be the absolute directory to the script, which includes the full path to the root of the web files.

This would be useful for more system related things, and not necessarily find other scripts within the website. The other would be the current path relevant to the web root, or base of the website itself. Here are some examples:

If the full path to your web server’s root directory is /var/www/html, this would be where your main website files live. However, the web server would see that as simply /, the root of the website itself starts where that leaves off. So, let’s say you have a directory that is accessible by going to your URL with the directory name after it like this:

http://www.somesite.com/mydir/

In your PHP script, if you grabbed the website relative directory, it would simply be “mydir”. The full or absolute directory would be “/var/www/html/mydir”. Make sense? The first one is relative to the website, the second is from the actual server root, showing where the files physically reside within the server file system.

OK, how do we get this information? Glad you asked!

To get the relative website path (just mydir from above), you would use something like this:

$directory = dirname($_SERVER['PHP_SELF']);
echo $directory;

This should return just the website relative path you are in. Now, to get the full path, there is a built in command for that in PHP and it works great, try:

$directory = getcwd();
echo $directory;

This should return the full file system path, it’s just that easy! Enjoy.

This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Tell me what you are thinking?