PHP - Locate current directory from url

I need to be able locate the last directory of a domain, for example: or

$currentdir = ''



$currentdir ='dir2'

Example code would be much appreciated.

Thanks in advance.
Who is Participating?
steelseth12Connect With a Mentor Commented:
$path =  dirname($_SERVER['PHP_SELF']);

$getslash = strrpos($path,"/");

$directory = substr($path,$getslash+1);

print $directory;
This should work for you.  Be sure to change the $base_dir to whatever your base path is for your web directory.


$base_dir = "/your/base/web/directory";
$script_dir = getcwd();

if ($script_dir == $base_dir) {
     $current_dir = "";
} else {
     $current_dir = array_pop(explode($script_dir, "/"));


If your file is in the base directory of your web site, I don't think steelseth12's method would work.  In that scenario, I think $_SERVER['PHP_SELF'] would return just the name of the file, which would then result in the $directory variable being set to that file name (minus the first character).
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Actually, I think I overlooked something in steelseth12's solution.  Because of the use of dirname(), you may end up with just a slash or a dot as the path.  If that were to happen, then substr is going to return FALSE to the $directory variable.  Technically, I think it would still work, though I'm not sure if it's really the best way to do it.  I don't know if that would be the most reliable, or safe, method of getting the current directory (especially since I don't know what you're using this for).
Luv2MuffAuthor Commented:
I accepted the answer from steelseth12

It was the first answer in, I have tested to 1 directory deep, and it seems to work perfectly.

Many, many thanks for all your help.

Ouch, 65 minutes vs. 66 minutes :)  Oh well, glad it works for you.  If you run into any issues, the answer I submitted should work without any problems.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.