dirname

(PHP 4, PHP 5)

dirname — Возвращает имя каталога из указанного пути

Описание

string dirname ( string $path )

Данная функция возвращает имя каталога, содержащегося в параметре path .

На платформах Windows в качестве разделителей имен директорий используются оба слэша (прямой / и обратный \). В других операционных системах разделителем служит прямой слэш (/).

Пример #1 Пример использования функции dirname()

<?php
$path 
"/etc/passwd";
$file dirname($path); // $file содержит "/etc"
?>

Замечание: Начиная с PHP версии 4.0.3, функция dirname() стала совместима со стандартом POSIX. Это, по существу, означает, что, если в path отсутствуют слэши, функция вернет точку ('.'), обозначающую текущий каталог. Иначе результатом выполнения функции будет являться значение параметра path с отброшенным завершающим /компонентом. Обратите внимание, что вы будете часто получать точку или слэш в ситуациях, в которых прежняя фунциональность dirname() возвращала бы пустую строку.

dirname() изменила своё поведение в PHP 4.3.0. Примеры:

<?php

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

//после PHP 4.3.0
dirname('c:/'); // returns 'c:'

?>

dirname() стала правильно обрабатывать двоичные данные начиная с версии PHP 5.0.0

См.также описание функций basename(), pathinfo() и realpath().

Коментарии

To get the directory of current included file:

<?php
dirname
(__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:

<?php
include_once(dirname(__FILE__) . '/database.class.php');
?>
2002-04-30 15:09:50
http://php5.kiev.ua/manual/ru/function.dirname.html
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:

<?php
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'); .
2003-01-08 12:20:29
http://php5.kiev.ua/manual/ru/function.dirname.html
dirname can be used to create self referencing web scripts with the following one liner.

<?php
$base_url 
str_replace($DOCUMENT_ROOT""dirname($PHP_SELF));
?>

Using this method on a file such as:

/home/mysite/public_html/wherever/whatever.php

will return:

/wherever

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

Example:

href='<?=$base_url?>/myscript.php'
2003-01-11 14:43:37
http://php5.kiev.ua/manual/ru/function.dirname.html
Code for write permissions check:

<?php
error_reporting
(E_ALL);
$dir_name '/var/www/virtual/phpintra/htdocs/php/';
do {
   
$b_is_writable is_writable($dir_name);
    echo 
sprintf("Dir[%s]Writable[%s]\n"$dir_name$b_is_writable'YES':'NO');
}while ((
$dir_name dirname($dir_name)) !='/');
?>
2003-01-14 09:02:17
http://php5.kiev.ua/manual/ru/function.dirname.html
You can use it to get parent directory:

dirname(dirname(__FILE__))

...include a file relative to file path:

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

..etc.
2004-01-01 20:41:25
http://php5.kiev.ua/manual/ru/function.dirname.html
Автор:
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:

<?php
 
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;
              break;
          }
      } while (
$dir !== ($dir dirname ($dir)));

      return (bool) @
$is_in_dir;
  }
?>
2005-04-27 18:31:05
http://php5.kiev.ua/manual/ru/function.dirname.html
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.

e.g. 

dirname('/usr/local/magic/bin');

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.
2005-06-24 09:52:20
http://php5.kiev.ua/manual/ru/function.dirname.html
Attention with this. Dirname likes to mess with the slashes.
On Windows, Apache: 

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

prints out

$_SERVER[PHP_SELF]: /index.php
Dirname($_SERVER[PHP_SELF]: \
2005-07-18 10:14:50
http://php5.kiev.ua/manual/ru/function.dirname.html
--- Edited by tularis@php.net ---
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);
}

current_dir();

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.
2005-08-10 13:15:09
http://php5.kiev.ua/manual/ru/function.dirname.html
The best way to get the absolute path of the folder of the currently parsed PHP script is:

<?php

if (DIRECTORY_SEPARATOR=='/')
 
$absolute_path dirname(__FILE__).'/';
else
 
$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.]
2006-07-10 09:52:16
http://php5.kiev.ua/manual/ru/function.dirname.html
Getting absolute path of the current script: 

<?php
dirname
(__FILE__)
?>

Getting webserver relative path of the current script...

<?php
function GetRelativePath($path)
{
   
$npath str_replace('\\''/'$path);
    return 
str_replace(GetVar('DOCUMENT_ROOT'), ''$npath);
}
?>

later on

<?php
GetRelativePath
(dirname(__FILE__));
?>

If anyone has a better way, get to the constructive critisism!
2006-10-24 14:35:10
http://php5.kiev.ua/manual/ru/function.dirname.html
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.

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

?>
2007-01-26 18:25:15
http://php5.kiev.ua/manual/ru/function.dirname.html
Автор:
Most mkpath() function I saw listed here seem long and convoluted.
Here's mine:

<?php
 
function mkpath($path)
  {
    if(@
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.
2007-09-10 13:55:35
http://php5.kiev.ua/manual/ru/function.dirname.html
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:
<?php
$containing_dir 
basename(dirname(__FILE__));
?>
2008-03-23 17:55:06
http://php5.kiev.ua/manual/ru/function.dirname.html
this little function gets the top level public directory 

eg. http://www.mysite.com/directory1/file.php 

or http://www.mysite.com/directory1/directory2/directory3/file.php

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

<?php
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);
   
    return 
$public_base;
}
?>
2008-05-12 02:31:30
http://php5.kiev.ua/manual/ru/function.dirname.html
Автор:
A simple way to show the www path to a folder containing a file...

echo "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
2008-06-04 16:01:10
http://php5.kiev.ua/manual/ru/function.dirname.html
Автор:
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:

<?php

// 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;

?>
2008-07-20 14:13:18
http://php5.kiev.ua/manual/ru/function.dirname.html
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, www.somehost.com/client/somepage.php, where the code above works great, but then wanted to put it on a subdomain, client.somehost.com/somepage.php, 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:

<?php
function safe_dirname($path)
{
   
$dirname dirname($path);
   return 
$dirname == '/' '' $dirname;
}
?>
2008-12-13 12:07:02
http://php5.kiev.ua/manual/ru/function.dirname.html
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.
2009-05-29 16:33:07
http://php5.kiev.ua/manual/ru/function.dirname.html
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_PATH',realpath('.'));
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.)
2009-11-25 08:06:53
http://php5.kiev.ua/manual/ru/function.dirname.html
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)))
2010-09-07 12:51:26
http://php5.kiev.ua/manual/ru/function.dirname.html
As usual, to include or require a file, we use this
<?php
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.
<?php
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
2011-06-26 23:54:14
http://php5.kiev.ua/manual/ru/function.dirname.html
If you want to get the parent parent directory of your script, you can use this:

<?php
 
//Example script path: home/content/en/script.php
 
$parentparentdir=basename(dirname(dirname(__FILE__)));
 echo 
$parentparentdir//will output 'content'
?>
2012-03-10 19:33:16
http://php5.kiev.ua/manual/ru/function.dirname.html
You can get best root path if you want to call a file from you project paths.

Make sure this define in your www/index.php

or the core file that inside www/ root.

<?php

/**
 * @def (string) DS - Directory separator.
 */
define("DS","/",true);

/**
 * @def (resource) BASE_PATH - get a base path.
 */
define('BASE_PATH',realpath(dirname(__FILE__)).DS,true);

?>

You can call any file any time without any problems

<?php

include BASE_PATH.'inc/class.php';

?>
2013-02-18 04:39:26
http://php5.kiev.ua/manual/ru/function.dirname.html
what about a recursive dirname. To get $count levels up in a directory.

<?php

function r_dirname($path$count=1){
    if (
$count 1){
       return 
dirname(r_dirname($path, --$count));
    }else{
       return 
dirname($path);
    }
}
2013-09-11 12:55:48
http://php5.kiev.ua/manual/ru/function.dirname.html
File located locally in: F:\localhost\www\Shaz3e-ResponsiveFramework\S3-CMS\_source

Localhost Path: http://s3lab.com/Shaz3e-ResponsiveFramework/S3-CMS/_source/

Example 1: dirname($_SERVER['PHP_SELF']); //output:  /Shaz3e-ResponsiveFramework/S3-CMS/_source

Example 2: "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']); //output:  http://s3lab.com/Shaz3e-ResponsiveFramework/S3-CMS/_source

Example 3: $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); //output:  s3lab.com/Shaz3e-ResponsiveFramework/S3-CMS/_source
2014-03-11 03:34:02
http://php5.kiev.ua/manual/ru/function.dirname.html
As of PHP 5.3.0, you can use __DIR__ as a replacement for dirname(__FILE__)
2014-10-22 10:51:19
http://php5.kiev.ua/manual/ru/function.dirname.html
Автор:
After PHP 7;
<?php
print dirname("/usr/local/lib"2); # /usr
?>

Before PHP 7;
<?php
print dirname(dirname("/usr/local/lib")); # /usr

# or
function dirname_with_levels($path$levels 1) {
    while (
$levels--) {
       
$path dirname($path);
    }
    return 
$path;
}
print 
dirname_with_levels("/usr/local/lib"2); # /usr
?>
2015-12-13 03:01:10
http://php5.kiev.ua/manual/ru/function.dirname.html
Be aware that if you call dirname(__FILE__) on Windows, you may get backslashes. If you then try to use str_replace() or preg_replace() to replace part of the path using forward slashes in your search pattern, there will be no match. You can normalize paths with $path = str_replace('\\',  '/' ,$path) before doing any transformations
2018-12-28 07:04:29
http://php5.kiev.ua/manual/ru/function.dirname.html

    Поддержать сайт на родительском проекте КГБ