Get Parent directory of Current URL using PHP dirname function

Suppose you are at a URL http://yoursite.domain/dir1/subdir2/subdir/file.php and want to get the 1st level Parent directory of this URL. Evidently, the URL of the parent Directory will be http://yoursite.domain/dir1/subdir2/subdir but the question is how to generate it automatically using PHP.


The answer is using PHP function dirname(). Using this, you can easily get any level of parent directories of the current URL. Before you check the code, how about having a look at the online demo first?

To know how to use dirname to get the parent directory of the required level of current URL, read on below!

The basic Usage of dirname() function:

The dirname function gives one level up directory name (absolute or relative according to the source provided) of the passed argument. The syntax is:


For example:

echo dirname('/mysite/mydir/mydir2/');

The output of the above code will be: /mysite/mydir

It can also be applied over Web URL. So the output of the following code will be:



Using dirname to get The parent directory of current working URL:

Now, we will see how to get the parent directory of the working URL. Say, my working URL is

Clearly, the parent directory of this URL is

Now all we need to do, is to pass this string through dirname function… Following is an example:

$url = '';
echo dirname($url);

The above code will output the result as shown before.

Getting certain level of parent directory using dirname:

Say, you want to get 2 level up directory name of the Working URL. So, you want to become

The answer is simple… We have to pass the URL through dirname function, for required number of levels… Obviously we can use a for loop to do this automatically.

$url = '';
$number = 2;
echo "<p>The $number level Parent Directory name of $url is</p>";
for($i=0; $i<$number; $i++) {
    $url = dirname($url);
echo '<blockquote>'.$url.'</blockquote>';

This will pass the URL 2 times through dirname function and will output the result.

Note that the above statement is equivalent to the following code [Provided that $number is 2]

$url = '';
//Pass it through two successive dirname
$url = dirname(dirname($url));
//Now echo the output
echo $url;

That was all. Check the Online Demonstration to try out yourself. Put any URL and enter the number of level you want to go up. Also download the source code to see how things are done!

I hope the information was useful for you. Don’t forget to give your feedback! Also if you face any problem, feel free to ask here!


  1. Pingback: Determine Plugin path n URL using Wordpress API functions | InTechgrity

    • Swashata Post author

      You will need to have htaccess rewrite for this. I shall write a new post on this sometime. You can simply google about htaccess rewrite.

Comments are closed.