|
dirname
Returns directory name component of path
(PHP 4, PHP 5)
Example 621. dirname() example<?php Related Examples ( Source code ) » dirname Examples ( Source code ) » Listing the Contents of a Directory with readdir() Examples ( Source code ) » Print all files under a directory Examples ( Source code ) » HTML form with a file input tag Examples ( Source code ) » dirname Examples ( Source code ) » pathinfo Code Examples / Notes » dirnamesoywiz
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. nsefton_nospam_
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 inconnu0215
To get the highest direcory, a simple method is : $dir=basename(dirname($path));
tapken
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'); info
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 "; echo "$www "; ?> 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 joel
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); phpcomm-david
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' ?> ludma
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"); not
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. ssl
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']) hans111
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__)))); } ?> legolas558 dot sourceforge comma net
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 tobylewis
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. hans111
Simple way to find out the current directory name: <?php function my_dir(){ $arfdn = explode('/', dirname($_SERVER['PHP_SELF'])); return end($arfdn); } ?> jo
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'); ?> tee cee
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. chris
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.
*~^-+=: *_* :=+-^~*
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/ ) zingus j. rinkle
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. timatscurvydotnewyorknets
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'])); rwf
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 holger thölking
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; } ?> cmnetworx
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: "; echo "$folder"; ?> dave
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'); . mat-vr
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! borisallan
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. legolas558 dot sourceforge comma net
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']; } ?> andrew
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. jon
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).'/'; xedecimal
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! degoede
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. temposeb
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" rudecoder
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' andrey
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)) !='/'); justin brimm
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("..")) ?>
klugg this-is-junk
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']) . ' '; ?> prints out $_SERVER[PHP_SELF]: /index.php Dirname($_SERVER[PHP_SELF]: \ zippy wonder idiot
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. parorrey
agreed fully to Tee Cee. putting: $array_uri = explode('/', $_SERVER['REQUEST_URI']); $current_dir = $array_uri[sizeof($array_uri)-2]; jaxolotl
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 renich
--- 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. philb
<?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"]); ?> jay jansheski
<? // 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(); ?> 23-jan-2005 01: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.
|
Change Languagebasename chgrp chmod chown clearstatcache copy delete dirname disk_free_space disk_total_space diskfreespace fclose feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents file fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype flock fnmatch fopen fpassthru fputcsv fputs fread fscanf fseek fstat ftell ftruncate fwrite glob is_dir is_executable is_file is_link is_readable is_uploaded_file is_writable is_writeable lchgrp lchown link linkinfo lstat mkdir move_uploaded_file parse_ini_file pathinfo pclose popen readfile readlink realpath rename rewind rmdir set_file_buffer stat symlink tempnam tmpfile touch umask unlink |