The Server Pages
:: TSP Menu
- Home
- Authors
- Glossary
- RSS Feed

:: Servers
- CPanel
- Hosting
- Linux
- Windows

:: Webmaster
- Databases
- Design
- Search Engines

:: Scripts
- Scripts

:: Documentation
- PHP Manual

:: Other
- Errors & Solutions
- TechPunt
- Wojjie

search for in the

disk_free_space> <delete
[edit] Last updated: Sat, 12 May 2012

view this page in


(PHP 4, PHP 5)

dirnameReturns parent directory's path


string dirname ( string $path )

Given a string containing the path of a file or directory, this function will return the parent directory's path.



A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

Return Values

Returns the path of the parent directory. If there are no slashes in path, a dot ('.') is returned, indicating the current directory. Otherwise, the returned string is path with any trailing /component removed.


Version Description
5.0.0 dirname() is now binary safe
4.0.3 dirname() was fixed to be POSIX-compliant.


Example #1 dirname() example

echo "1) " dirname("/etc/passwd") . PHP_EOL// 1) /etc
echo "2) " dirname("/etc/") . PHP_EOL// 2) / (or \ on Windows)
echo "3) " dirname("."); // 3) .



dirname() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..".


dirname() is locale aware, so for it to see the correct directory name with multibyte character paths, the matching locale must be set using the setlocale() function.


Since PHP 4.3.0, you will often get a slash or a dot back from dirname() in situations where the older functionality would have given you the empty string.

Check the following change example:


//before PHP 4.3.0
dirname('c:/'); // returned '.'

//after PHP 4.3.0
dirname('c:/x'); // returns 'c:\'
dirname('c:/Temp/x'); // returns 'c:/Temp'
dirname('/x'); // returns '\'


See Also

  • basename() - Returns trailing name component of path
  • pathinfo() - Returns information about a file path
  • realpath() - Returns canonicalized absolute pathname

disk_free_space> <delete
[edit] Last updated: Sat, 12 May 2012
add a note add a note User Contributed Notes dirname
minimalist at intelligence dot com 10-Mar-2012 05:33
If you want to get the parent parent directory of your script, you can use this:

//Example script path: home/content/en/script.php
$parentparentdir; //will output 'content'
nhl261 at yahoo dot com 26-Jun-2011 08:54
As usual, to include or require a file, we use this
require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'my_file.php';

in rare case, we have current file existing at the root directory, dirname would return C:\ or / , then the line above contains 2 slashes \\ or //
To handle this this case, we use rtrim to clear slashes.
require rtrim(dirname(__FILE__), '/\\') . DIRECTORY_SEPARATOR . 'my_file.php';

Also, another use of dirname is to get virtual directory (url path), the issue is the same as above, we have to check and process before concatenating strings
subzey at immelman dot ru 07-Sep-2010 09:51
In some situations (I can't locate the dependencies) basename and dirname may return incorrect values if parsed string is in UTF-8.

Like, dirname("glossary/задний-фокус") will return "glossary" and basename("glossary/задний-фокус") will return "-фокус".

Quickfix is
str_replace("!$!", "", dirname(str_replace("/", "!$!/!$!", $q)))
webyazilimci84 at gmail dot com 25-Nov-2009 06:06
In my mvc based framework i make BASE_PATH and BASE_URL definitions like the following and both work well in the framework without problem.

index.php :

define('BASE_URL', dirname($_SERVER["SCRIPT_NAME"]));

BASE_PATH is for server side inclusions.
BASE_URL is for client side inclusions (scripts, css files, images etc.)
ken dot forslund at hp dot com 29-May-2009 01:33
A key problem to hierarchical include trees is that PHP processes include paths relative to the original file, not the current including file.

A solution to that, is to prefix all include paths with:
<?php str_replace('//','/',dirname(__FILE__)); ?>

this will generate a base path relative to the current file, which will then allow an include behavior similar to C/C++.

thus, to include a file that is 1 in the parent directory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'../parent.php'); ?>

to include a file that is in the same directory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'neighbor.php'); ?>

to include a file that is in a subdirectory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'folder/sub.php'); ?>

Notice that all paths we reference must NOT begin with a /, and must be relative to the current file, in order to concatenate correctly.
joe dot naylor at gmail dot com 13-Dec-2008 10:07
The dirname function does not usually return a slash on the end, which might encourage you to create links using code like this:
$url = dirname($_SERVER['PHP_SELF']) . '/somepage.php';

However dirname returns a slash if the path you specify is the root, so $url in that case would become '//somepage.php'.  If you put that URL as the action on a form, for example, submitting the form will try to go to http://somepage.php.

I ran into this when I wrote a site on a url with a path,, where the code above works great, but then wanted to put it on a subdomain,, where things started breaking.

The best solution would be to create a function that generates absolute URLs and use that throughout the site, but creating a safe_dirname function (and an htaccess rewrite to fix double-slashes just in case) fixed the issue for me:

function safe_dirname($path)
$dirname = dirname($path);
$dirname == '/' ? '' : $dirname;
ricardo dot ferro at gmail dot com 22-Oct-2008 08:11
dirname can be used to fix paths:

function fixPath ($path)
dirname($path . '/.');

fixPath('/one');                  // '/one'
fixPath('/one/');                 // '/one'
fixPath('/one//two');          // '/one/two'
fixPath('/one////two////');   // '/one/two'
Tom 20-Jul-2008 11:13
Expanding on Anonymous' comment, this is not necessarily correct. If the user is using a secure protocol, this URL is inaccurate. This will work properly:


// Is the user using HTTPS?
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';

// Complete the URL
$url .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);

// echo the URL
echo $url;

Anonymous 04-Jun-2008 01:01
A simple way to show the www path to a folder containing a file...

echo "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
rmahase at gmail dot com 11-May-2008 11:31
this little function gets the top level public directory



will both return "directory1" ...which is the top level directory

function public_base_directory()
//get public directory structure eg "/top/second/third"
$public_directory = dirname($_SERVER['PHP_SELF']);
//place each directory into array
$directory_array = explode('/', $public_directory);
//get highest or top level in array of directory strings
$public_base = max($directory_array);
ts at dev dot websafe dot pl 23-Mar-2008 03:55
Inside of script.php I needed to know the name of the containing directory. For example, if my script was in '/var/www/htdocs/website/somedir/script.php' i needed to know 'somedir' in a unified way.

The solution is:
= basename(dirname(__FILE__));
Zingus J. Rinkle 10-Sep-2007 10:55
Most mkpath() function I saw listed here seem long and convoluted.
Here's mine:

function mkpath($path)
mkdir($path) or file_exists($path)) return true;
    return (
mkpath(dirname($path)) and mkdir($path));

Untested on windows, but dirname() manual says it should work.
hans111 at yahoo dot com 26-Jan-2007 04:25
The same function but a bit improved, will use REQUEST_URI, if not available, will use PHP_SELF and if not available will use __FILE__, in this case, the function MUST be in the same file. It should work, both under Windows and *NIX.

function my_dir(){
end(explode('/', dirname(!empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : !empty($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : str_replace('\\','/',__FILE__))));

Xedecimal at gmail dot com 24-Oct-2006 11:35
Getting absolute path of the current script:


Getting webserver relative path of the current script...

function GetRelativePath($path)
$npath = str_replace('\\', '/', $path);
str_replace(GetVar('DOCUMENT_ROOT'), '', $npath);

later on


If anyone has a better way, get to the constructive critisism!
legolas558 dot sourceforge comma net 10-Jul-2006 06:52
The best way to get the absolute path of the folder of the currently parsed PHP script is:


$absolute_path = dirname(__FILE__).'/';
$absolute_path = str_replace('\\', '/', dirname(__FILE__)).'/';


This will result in an absolute unix-style path which works ok also on PHP5 under Windows, where mixing '\' and '/' may give troubles.

[EDIT by danbrown AT php DOT net: Applied author-supplied fix from follow-up note.]
phpcomm-david at tulloh dot id dot au 01-Mar-2006 09:41
This is dirty little trick to allow dirname() to work with paths with and without files.


Some examples:
basename($var) == '/foo/bar'
basename($var.'a') == '/foo/bar'

basename($var) == '/foo'
basename($var.'a') == '/foo/bar'
renich at woralelandia dot com 10-Aug-2005 10:15
--- Edited by ---
You could also have a look at the getcwd() function
--- End Edit ---

A nice "current directory" function.

function current_dir()
$path = dirname($_SERVER[PHP_SELF]);
$position = strrpos($path,'/') + 1;
print substr($path,$position);


I find this usefull for a lot of stuff! You can maintain a modular site with dir names as modules names. At least I would like PHP guys to add this to the function list!

If there is anything out there like it, please tell me.
klugg this-is-junk at tlen dot pl 18-Jul-2005 07:14
Attention with this. Dirname likes to mess with the slashes.
On Windows, Apache:

echo '$_SERVER[PHP_SELF]: ' . $_SERVER['PHP_SELF'] . '<br />';
'Dirname($_SERVER[PHP_SELF]: ' . dirname($_SERVER['PHP_SELF']) . '<br>';

prints out

$_SERVER[PHP_SELF]: /index.php
Dirname($_SERVER[PHP_SELF]: \
tobylewis at mac dot com 24-Jun-2005 06:52
Since the paths in the examples given only have two parts (e.g. "/etc/passwd") it is not obvious whether dirname returns the single path element of the parent directory or whether it returns the whole path up to and including the parent directory.  From experimentation it appears to be the latter.



returns '/usr/local/magic'  and not just 'magic'

Also it is not immediately obvious that dirname effectively returns the parent directory of the last item of the path regardless of whether the last item is a directory or a file.  (i.e. one might think that if the path given was a directory then dirname would return the entire original path since that is a directory name.)

Further the presense of a directory separator at the end of the path does not necessarily indicate that last item of the path is a directory, and so

dirname('/usr/local/magic/bin/');  #note final '/'

would return the same result as in my example above.

In short this seems to be more of a string manipulation function that strips off the last non-null file or directory element off of a path string.
27-Apr-2005 03:31
If you merely want to find out wether a certain file is located within or underneath a certain directory or not, e.g. for White List validation, the following function might be useful to you:

function in_dir ($file, $in_dir)
$dir    = realpath ($file);
$in_dir = realpath ($in_dir);

      if (!
is_dir ($file)) {
$dir = dirname ($file);

      do {
          if (
$dir === $in_dir) {
$is_in_dir = TRUE;
      } while (
$dir !== ($dir = dirname ($dir)));

      return (bool) @
soywiz at hotmail dot com 01-Jan-2004 06:41
You can use it to get parent directory:


...include a file relative to file path:

include(dirname(__FILE__) . '/path/relative/file_to_include.php');

andrey at php dot net 14-Jan-2003 07:02
Code for write permissions check:

$dir_name = '/var/www/virtual/phpintra/htdocs/php/';
do {
$b_is_writable = is_writable($dir_name);
sprintf("Dir[%s]Writable[%s]\n", $dir_name, $b_is_writable? 'YES':'NO');
}while ((
$dir_name = dirname($dir_name)) !='/');
rudecoder at yahoo dot com 11-Jan-2003 12:43
dirname can be used to create self referencing web scripts with the following one liner.

= str_replace($DOCUMENT_ROOT, "", dirname($PHP_SELF));

Using this method on a file such as:


will return:


Now $base_url can be used in your HTML to reference other scripts in the same directory.


dave at corecomm dot us 08-Jan-2003 10:20
I very much appreciated Fredrich Echol's suggestion (rwf at gpcom dot net) of how to find a base path, but found that it failed when the initial script was already in the root folder -- dirname('/rootscript.php')=='/' and dirname('/include/includescript.php')=='/include' which have the same number of slashes. This variation is what I'm now using:

if (!defined("BASE_PATH")) define('BASE_PATH', dirname($_SERVER['SCRIPT_NAME'])=='/' ? './' : str_repeat("../"substr_count(dirname($_SERVER["SCRIPT_NAME"]), "/")));

This explicitly checks for the root path (/) and uses './' as the base path if we're in the root folder.
I put this at/near the top of any file that calls another. (I used define for my own convenience; should work just fine with variables and without testing to see if you already did it.)

Note that in both cases (root-folder script and non-root-folder script), BASE_PATH will include a trailing slash. At least with Apache on Darwin (Mac OS X), you can include(BASE_PATH.'/myfile.php'); and the doubled slash won't cause any problems, giving the same result as include(BASE_PATH.'myfile.php'); .
rwf at gpcom dot net 01-Aug-2002 04:08
If you want relative includes like C or C++ has, you need to find out where you are in relation to the base path of the server. That is, if you are two levels into the "htdocs" directory in apache, then you need to add "../../" to the begining of the include to get back to the base directory. That's simple. What's NOT so simple is when you have "nested" included files.

Continuing the example above, if you have a file example.php and it includes "../../lib.php" and lib.php includes "lib2.php" guess where "lib2.php" needs to be located? In the same directory as example.php! What you really wanted was to have lib.php and lib2.php in the same directory... To get that result you need to include "../../lib2.php" in lib.php... But wait, now it won't work if the original example.php file is in any other place but two levels deep!

The answer to the problem is this: find the number of levels you are currently into the base directory and add as many "../" as you need to the begining of the include filename in EVERY include file.

Here's an example:

$BasePath = str_repeat("../", substr_count(dirname($_SERVER["SCRIPT_NAME"]), "/"));


Notice that we're adding the $BasePath and the name of the file we want together to get the full path. It will look like this: "../../lib.php"


Notice here that BasePath has already been defined so we don't know or care what BasePath looks like, only that it now allows us to use a relative path to lib2.php since it automatically adds the number of "../" needed to get to it from the original example.php that the server executed. The path here will look like this: "../../lib2.php"

And now we can easily have lib.php and lib2.php in the same directory, and have lib.php include lib2.php as if it's a relative include.

Pretty simple, no? :)

-Fredric Echols
tapken at engter dot de 30-Apr-2002 12:09
To get the directory of current included file:


For example, if a script called 'database.init.php' which is included from anywhere on the filesystem wants to include the script 'database.class.php', which lays in the same directory, you can use:

include_once(dirname(__FILE__) . '/database.class.php');

show source | credits | sitemap | contact | advertising | mirror sites