Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

dirname

(PHP 3, 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().



disk_free_space> <delete
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
dirname
joel at joelpittet dot com
11-Sep-2007 05:10
This is silly:
dirname(dirname( dirname( dirname(dirname( dirname( dirname(__FILE__))))))); // This is rediculous
        
function recursiveDirName($file, $x){
    if($x > 0) return recursiveDirName( dirname($file), $x-1 );
    return $file;
}

This is much easier:
$file = recursiveDirName(__FILE__, 7);
Zingus J. Rinkle
10-Sep-2007 10:55
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.
Justin Brimm
09-Sep-2007 06:36
Because <?php dirname() ?> doesn't support relative paths, I had to sit and think a bit about the easiest method to get the name of the directory above the current directory. I ended up coming with this little solution: <?php basename(realpath("..")) ?>
Chris
03-Jul-2007 06:04
No, getcwd() is a different beast - it returns the current working directory, which may often be different to the directory in which the current file resides.  getcwd() will be Ok so long as you're dealing with single, flat directory structures.
mat-vr at hotmail dot com
23-Jun-2007 07:57
I see some of you are writing about the simplest way of getting the current directory... why not just use this:

$currentdic = getcwd();

yea that's all!
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.

<?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__))));
}

?>
hans111 at yahoo dot com
26-Jan-2007 02:45
Simple way to find out the current directory name:
<?php
function my_dir(){
   
$arfdn = explode('/', dirname($_SERVER['PHP_SELF']));
    return
end($arfdn);
}
?>
Xedecimal at gmail dot com
24-Oct-2006 11:35
Getting absolute path of the current script:

dirname(__FILE__)

Getting webserver relative path of the current script...

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

later on

GetRelativePath(dirname(__FILE__));

If anyone has a better way, get to the constructive critisism!
parorrey at yahoo dot com
25-Sep-2006 10:37
agreed fully to Tee Cee.

putting:

$array_uri = explode('/', $_SERVER['REQUEST_URI']);
$current_dir = $array_uri[sizeof($array_uri)-2];
Tee Cee
20-Aug-2006 05:21
Obviously, what you have to do is use functions that are meant to work on URLs and not filesystem paths. There is a big difference.

All this dirname hackery can be avoided if you just code a urldirname that finds the last / in the file and does a suitable substring operation, but I'm currently too lazy to write the code.
legolas558 dot sourceforge comma net
12-Jul-2006 10:02
The mixed slashes issues was present on Windows XP with
PHP 4.4.1, it has been fixed on later versions.

Fix: in the below note a single slash '\' is intended to be replaced, and not two
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:

<?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.
legolas558 dot sourceforge comma net
10-Jul-2006 04:35
I have to disagree with <jo _at durchholz dout org>

In some installations (< 4.4.1, cannot be more precise) $_SERVER['REQUEST_URI'] is not set, I used the below code to fix it

<?php

if (!isset($_SERVER['REQUEST_URI'])) {
   
$_SERVER['REQUEST_URI'] = substr($_SERVER['PHP_SELF'],1);
    if (isset(
$_SERVER['QUERY_STRING'])) $_SERVER['REQUEST_URI'].='?'.$_SERVER['QUERY_STRING'];
}

?>
jo at durchholz dot org
21-Mar-2006 02:40
OK, I'll bite :-)

Things that could be improved are:

1. PHP_SELF isn't always reliable. (Particularly various (mis-)configured FastCgi installations.) REQUEST_URI is, and it's reasonably easy to parse. Even better, REQUEST_URI also contains the server name.
2. When concatenating, you don't need that initial empty string.
3. dirname() has a borderline case (at least in 4.4.4): if the URL ends with a slash, the path part preceding it is stripped, too.
I.e. if the script is called as http://example.com/path/to/script/index.php, dirname() will do the Right Thing, but http://example.com/path/to/script/ will come out as http://example.com/path/to. (*Very* bewildering if the customer phones you about that...)
Luckily, that's easy to fix by adding a letter (actually anything but a slash) to the URL.

Giving:

<?php
list ($url, $query_string)
  =
explode ('?', $_SERVER ['REQUEST_URI'], 2);
$urldir = dirname ($url . 'x');
?>
CMNetworx
20-Mar-2006 10:49
I wanted to get just the current folder that the document is in, but not the rest of the url, so here is a simple replacement array. Might be a little more code than neccessary..

<?
$DocName = "" . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
$DirNow = dirname($DocName);

$drop = array("www.", "yourwebsite", ".com/");
# here you drop the url, ex: www.yourwebsite.com/
$pickup = array("", "", "");

$folder = str_replace($drop, $pickup, $DirNow);
echo "Your Current Folder is:<br>";
echo "$folder";
?>
borisallan at socialenquiry dot org
04-Mar-2006 03:52
I needed to refer to a directory, one up the tree, so that I had an explicit rather than relative anchor. I couldn't find a function, so I invented:

  $DocName = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
  $DirNow = dirname($DocName);
  $DirUp = dirname($DirNow);

which seems to work.
Cheers. BoRiS.
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.

basename($var.'a');

Some examples:
<?php
$var
='/foo/bar/file';
basename($var) == '/foo/bar'
basename($var.'a') == '/foo/bar'

$var='/foo/bar/';
basename($var) == '/foo'
basename($var.'a') == '/foo/bar'
?>
jay jansheski
27-Feb-2006 06:42
<?
// gets the folder name of the current script

function this_folder_name($path){
    if (!$path){$path=$_SERVER['PHP_SELF'];}
    $current_directory = dirname($path);
    $current_directory = str_replace('\\','/',$current_directory);
    $current_directory = explode('/',$current_directory);
    $current_directory = end($current_directory);
    return $current_directory;
}
print this_folder_name();
?>
ssl at bokehman dot com
21-Sep-2005 01:55
The way this function plays with slashes in windows is a pain so if you are trying to get the current directory I would use the following instead:

str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF'])
renich at woralelandia dot com
10-Aug-2005 10:15
--- 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.
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:

<?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]: \
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.

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.
Holger Th
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571