 |
dirname (PHP 3, PHP 4, PHP 5) dirname -- 返回路径中的目录部分 说明string dirname ( string path )
给出一个包含有指向一个文件的全路径的字符串,本函数返回去掉文件名后的目录名。
在 Windows 中,斜线(/)和反斜线(\)都可以用作目录分隔符。在其它环境下是斜线(/)。
例子 1. dirname() 例子
<?php $path = "/etc/passwd"; $file = dirname($path); // $file is set to "/etc" ?>
|
|
注:
在 PHP 4.0.3 中,dirname() 被修正为
POSIX 兼容。本质上就意味着如果在 path
中没有斜线,则返回一个点('.'),表示当前目录。否则返回的是把
path 中结尾的
/component(最后一个斜线以及后面部分)去掉之后的字符串。注意这意味着在老的函数返回一个空字符串的情形下你通常从
dirname() 得到的是斜线或者一个点。
dirname() 从 PHP 4.3.0 开始有所改变
请看以下例子:
dirname() 的操作从 PHP 5.0.0 版开始是二进制安全的。
参见 basename(),pathinfo()
和 realpath()。
jo at durchholz dot org
22-Mar-2006 06: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
21-Mar-2006 02: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
05-Mar-2006 07: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
02-Mar-2006 01: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
28-Feb-2006 10: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
22-Sep-2005 04: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
11-Aug-2005 01: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 10: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 09: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 Thlking
28-Apr-2005 06: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:
<?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;
}
?>
Jaxolotl
24-Feb-2005 01:34
A simple way to have the complete URI of your actual "browsed" page for, as example, W3C css-validation link, or any time you need it, is:
$my_uri = "http://" . $_SERVER['HTTP_HOST'] . $HTTP_SERVER_VARS["SCRIPT_NAME"];
then
<?php echo ("$my_uri");?> as needed
23-Jan-2005 09:09
<<The path '/home/users/bob/' refers to the file 'bob' in directory '/home/users/', not the file '' in directory '/home/users/bob/.'>>, in fact no, it's the same thing.
not AT available DOT com
08-Jan-2005 01:13
There is no distinction between a directory and a file. This is how dirname() and basename() work. A directory *is* a file.
There is no such thing as a path to a non-existing file. The path '/home/users/bob/' refers to the file 'bob' in directory '/home/users/', not the file '' in directory '/home/users/bob/'. This is trivial.
Given the path '/etc/conf/sample', there is no way of determining whether 'sample' is a file or a directory just by looking at it. Think about that.
temposeb at free dot fr
07-Jun-2004 05:33
Doc : Given a string containing a path to a file
You _must_ specify a filename. Take care if you don't do that...
<?php
echo dirname('/folder/anotherone/') ;
?>
... will output "/folder" and not "/folder/anotherone"
zippy wonder idiot at yahoo dot com
24-Mar-2004 06:40
Andrew,
There are certainly good reasons to use relative includes, though I agree they usually should not be used exclusively. Here's a couple of common situations:
1) You do not have control over the web server on which you're developing. If you want your pages to work even if your {ISP,employer,friend,etc.} rearranges their server -- particularly Apache's user_dir -- then relative includes are the way to go. Your pages will work if they're at "http://www.host.tld/~user/", "http://host.tld/user/", or even "http://user.host.tld/".
2) You are developing a script or set of scripts for distribution. You don't want to force your users to rearrange their web server to allow includes from /includes/my-files before they can use your script, after all.
On my own server, for example, I keep all site-wide PHP and JavaScript in /scripts so that I don't have to worry about where they're being called from. The include files used by my media library, however, are in a scripts subdirectory of the folder the main script runs in. This also makes development easier; the development and production versions simply reside in different folders, allowing them to use different versions of the include files without altering the include statements.
andrew at i dot love dot spam dot majiclab dot com
30-Jan-2004 03:24
I am not understanding why everyone seems to want to use relative includes so much.
<?php
include("{$_SERVER['DOCUMENT_ROOT']}/includes/my_include.php");
?>
That will work in any script that is in any single folder on your entire website. No relative paths to mess with. You can just put all your includes in the same folder, and have different names for them if you want.
soywiz at hotmail dot com
02-Jan-2004 10:41
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.
degoede at tomaatnet dot nl
26-Jun-2003 10:58
Easy to have config functionality using dirname function.
inc.config.php:
===============================
/* UNC path to include file, plus trailing slash.
Convert back-slashes to slashes, always, on linux there will be none to replace, but who cares.
Use str_replace, as this is the fastest on simple replacements, according to php.net. */
$unc = str_replace( "\\\\", "/", dirname( __FILE__ ) . "/" ) ;
/* Remove the UNC path to this file from the UNC path to the main php script that included this file, only keeping any subfolder names, relative to this file's UNC. */
$url = str_replace( $unc, "", $_SERVER["SCRIPT_FILENAME"] ? $_SERVER["SCRIPT_FILENAME"] : $HTTP_SERVER_VARS["SCRIPT_FILENAME"] ) ;
/* Remove the value obtained from the calling php script's URL, to get the URL to this file.*/
$url = str_replace( $url, "", $_SERVER["SCRIPT_NAME"] ? $_SERVER["SCRIPT_NAME"] : $HTTP_SERVER_VARS["SCRIPT_NAME"] ) ;
/* Make a general purpose configuration data array. */
$Config["root"]["unc"] = $unc ;
$Config["root"]["url"] = $url ;
$Config["dir"]["images"] = "images/" ;
$Config["dir"]["include"] = "include/" ;
/* use functions to keep the interface simple and, seperate interface from internal functioning. */
function get_fullpath( $type, $dir )
{
global $Config ;
$FullPath = $Config["root"][$type] ;
$FullPath .= $Config["dir"][$dir] ;
return ( $FullPath ) ;
}
function get_unc( $dir, $file )
{
return ( get_fullpath( "unc", $dir ) . $file ) ;
}
function get_url( $dir, $file )
{
return ( get_fullpath( "url", $dir ) . $file ) ;
}
some_file.php:
===============================
include_once ( ../../inc.config.php ) ;
include_once ( get_unc( "include", "inc.some_include.php" ) ) ;
Now you only need to worry about a relative path once.
philb at gmx dot net
25-May-2003 11:37
<?php
// if you like put this into an include file
function ShowDirModTime($FullPath) {
$BasePath = dirname ($FullPath);
$time = filectime($BasePath);
$time=time()-$time;
$weeks=$time/604800;
$days=($time%604800)/86400;
$hours=(($time%604800)%86400)/3600;
$minutes=((($time%604800)%86400)%3600)/60;
$seconds=(((($time%604800)%86400)%3600)%60);
$timestring='[ ';
if(round($days)) $timestring.=round($days)."d ";
if(round($hours)) $timestring.=round($hours)."h ";
if(round($minutes)) $timestring.=round($minutes)."m ";
if(!round($minutes)&&!round($hours)&&!round($days)) $timestring.="".round($seconds)."s ";
$timestring.=']';
echo $timestring;
}
?>
<?php
// execute like this...
echo "dir last updated ";
ShowDirModTime($HTTP_SERVER_VARS["PATH_TRANSLATED"]);
?>
info at gieson dot com
15-May-2003 09:40
This one will put both the "www" and "file" path into an easy to transport array.
<?php
// build the www path:
$me = $_SERVER['PHP_SELF'];
$Apathweb = explode("/", $me);
$myFileName = array_pop($Apathweb);
$pathweb = implode("/", $Apathweb);
$myURL = "http://".$_SERVER['HTTP_HOST'].$pathweb."/".$myFileName;
$PAGE_BASE['www'] = $myURL;
// build the file path:
strstr( PHP_OS, "WIN") ? $strPathSeparator = "\\" : $strPathSeparator = "/";
$pathfile = getcwd ();
$PAGE_BASE['physical'] = $pathfile.$strPathSeparator.$myFileName;
// this is so you can verify the results:
$www = $PAGE_BASE['www'];
$physical = $PAGE_BASE['physical'];
echo "$physical<p>";
echo "$www<p>";
?>
The following will return something like:
Windows:
F:\dev\Inetpub\wwwroot\somedirectory\index.php
http://devserver/somedirectory/index.php
Unix:
/home/somepathto/gieson.com/webroot/index.php
http://www.gieson.com/index.php
*~^-+=:[*_*]:=+-^~*
22-Feb-2003 12:00
My name is Alex but you can call me WindEagle
my website is windeagle.tk
my email is az[at]windeagle.tk
jon at PLEASE DO NOT SPAM ME sdsc edu
here is a better version of your script
function PATH($DIR,$URL){
$DIR=preg_split("/[\/\\\]/",dirname($DIR));
$URL=preg_split("/[\/\\\]/",dirname($URL));
$cDIR = count($DIR);
$cURL = count($URL);
$min = min($cDIR, $cURL);
for($x=1;$x<=$min;$x++){
if($DIR[$cDIR-$x]==$URL[$cURL-$x]){ // path matches
unset($DIR[$cDIR-$x],$URL[$cURL-$x]); // erase any common elements
}else{break;}} // all that's left is uncommon elements
// just incase $DIR or $URL equals "//"
$DIR = ereg_replace("//","/",join('/',$DIR)."/");
$URL = ereg_replace("//","/",join('/',$URL)."/");
return array("DIR" => $DIR,"URL" => $URL);}
example:
lets say that
for Win32
$_SERVER['SCRIPT_FILENAME']="C:\web\path\cgi-bin\script.php"
for Unix
$_SERVER['SCRIPT_FILENAME']="/web/path/cgi-bin/script.php"
$_SERVER['SCRIPT_NAME']="/~sn/cgi-bin/script.php"
PATH($_SERVER['SCRIPT_FILENAME'],$_SERVER['SCRIPT_NAME'])
return:
Array
(
for Win32
[DIR] => C:/web/path/
for Unix
[DIR] => /web/path/
[URL] => /~sn/
)
jon at PLEASE DO NOT SPAM ME sdsc edu
15-Feb-2003 05:22
Here's a lil' code I cooked up to figure out the base directories, as far as filesystem vs. URLs. This is very helpful for, say an image that you want to use getimagesize(); on, but only have the URL oriented directory. You can then use str_replace(); or preg_replace(); and swap the values out easily!
Note that in order for it to work, you must include the pointer ($big = &$y), rather than simply copying ($big = $y).
// separate each dir into array elements
$x = explode('/', dirname($_SERVER['SCRIPT_FILENAME']));
$y = explode('/', dirname($_SERVER['SCRIPT_NAME']));
$countX = count($x);
$countY = count($y);
$max = max($countX, $countY);
$min = min($countX, $countY);
$dif = $max-$min;
if (isset($x[$max-1])) { // $x is the biggest
$big = &$x; // make $big a pointer to $x
$lil = &$y; // make $lil a pointer to $y
} else { // $y is the biggest
$big = &$y; // make $big a pointer to $y
$lil = &$x; // make $lil a pointer to $x
}
for($i=$max-1;$i>=$dif; $i--) {
if ($big[$i]==$lil[$i-$dif]) { // path matches
unset($big[$i], $lil[$i-$dif]); // erase any common elements
}
}
// all that's left is uncommon elements, join array(s)
$root_dir = join('/', $x).'/';
$root_url = join('/', $y).'/';
andrey at php dot net
14-Jan-2003 11:02
Code for write permissions check:
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)) !='/');
rudecoder at yahoo dot com
12-Jan-2003 04:43
dirname can be used to create self referencing web scripts with the following one liner.
$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'
dave at corecomm dot us
09-Jan-2003 02: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'); .
ludma at pochtamt dot ru
27-Dec-2002 12:35
This function does a correct way to a directory on a server,
it does not recognize only such ways as
http://???/script.php?dir=/ok/index.php
function url_dir($url) {
if (preg_match('/(.*)\/([^\/\.?]+)$/i', $url)) {
$t_dir = preg_replace('/[^\/]$/', '\\0/', $url);
} else {
$t_dir = preg_replace(
array('/(https?:\/\/)?(\w+\.)?(\w+\.'
.'[a-z]{2,4})(.*)\/([^\/]*)$/','/[^\/]$/'),
array('\\1\\2\\3\\4','\\0/'), $url);
}
return $t_dir;
}
Test:
$dir = url_dir("http://www.roja.ru/path/?ok=1&r=1");
nsefton_nospam_ at hotmail dot com
28-Aug-2002 11:03
Well i had this same problem, includes including files and how to get to overcome the problem of the first file can see the second, but the second does not know where it is being called from, and thus cant call the third file, so i came up with this solution...
<?php
function getPath() {
// get position of current file
$path = $GLOBALS["PATH_INFO"];
// save a few nanaseconds, has this been done before,
// has the global variable been set ?
if (!isset($definedPath)) {
// is file in root already ?
if (strrpos($path,"/")!=0) {
// there is probably a quicker way to count
// the "/"s in the path
$path=explode("/",$path);
$s="";
for ($i=0;$i<count($path)-1;$i++) {
if ($path[$i]!="") {
// add the number of "../"s required
$s.="../";
}
}
// declare a global variable so you dont have to
// do this again, and return the variable
global $definedPath;
$definedPath=$s;
return $definedPath;
}
} else {
// just return what it worked out before, function
// only really runs once
return $definedPath;
}
}
include getPath() . "my_include_path/header.inc";
include getPath() . "includes/somethingelse.inc";
//above file is at mydomain.com/includes/somethingelse.inc
include getPath() . "includes/footer.inc";
?>
So basically, this finds the "path back home" and from there it knows it's way around. I like Fredric's solution ( even tho I dont understand it :P ) but i thought I'd share what I've done (with room for improvement i'm sure).
Noel
rwf at gpcom dot net
02-Aug-2002 07: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:
example.php
------------
$BasePath = str_repeat("../", substr_count(dirname($_SERVER["SCRIPT_NAME"]), "/"));
require_once($BasePath."lib.php");
------------
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"
lib.php
------
require_once($BasePath."lib2.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
timATscurvyDOTnewyorkNETs
22-May-2002 07:45
if you want to know the *File System* (not web) Absolute Path (expanding the links) of the script that's currently being executed, try this:
$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
tapken at engter dot de
01-May-2002 03:09
To get the directory of current included file:
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:
include_once(dirname(__FILE__) . '/database.class.php');
inconnu0215 at noos dot fr
28-Mar-2002 05:13
To get the highest direcory, a simple method is : $dir=basename(dirname($path));
|  |