PHP Doku:: Liefert Informationen über einen Dateipfad - function.pathinfo.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzDateisystemrelevante ErweiterungenDateisystemDateisystem-Funktionenpathinfo

Ein Service von Reinhard Neidl - Webprogrammierung.

Dateisystem-Funktionen

<<parse_ini_string

pclose>>

pathinfo

(PHP 4 >= 4.0.3, PHP 5)

pathinfoLiefert Informationen über einen Dateipfad

Beschreibung

mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

pathinfo() gibt ein assoziatives Array mit Informationen über einen Dateipfad (path) zurück.

Parameter-Liste

path

Der zu prüfende Dateipfad.

options

Sie können mit dem optionalen Parameter options angeben, welche Elemente zurückgeben werden. Verwenden können Sie die Konstanten PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION und PATHINFO_FILENAME. Standardmäßig werden alle Elemente zurückgegeben.

Rückgabewerte

Die folgenden assoziativen array-Elemente werden zurückgegeben: dirname, basename, extension (falls vorhanden) und filename.

Falls options genutzt wird, gibt diese Funktion einen string zurück sofern nicht alle Elemente angefordert werden.

Changelog

Version Beschreibung
5.2.0 Die PATHINFO_FILENAME-Konstante wurde hinzugefügt.

Beispiele

Beispiel #1 pathinfo()-Beispiel

<?php
$path_parts 
pathinfo('/www/htdocs/inc/lib.inc.php');

echo 
$path_parts['dirname'], "\n";
echo 
$path_parts['basename'], "\n";
echo 
$path_parts['extension'], "\n";
echo 
$path_parts['filename'], "\n"// seit PHP 5.2.0
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

/www/htdocs/inc
lib.inc.php
php
lib.inc

Anmerkungen

Hinweis:

Informationen über das Wiederauffinden der aktuellen Pfadinformation finden Sie unter Vordefinierte Variablen.

Hinweis:

pathinfo() berücksichtigt die locale-Einstellung. Um den Pfad mit Multibyte-Zeichen korrekt parsen zu können, muss die entsprechende locale mit der setlocale()-Funktion gesetzt werden.

Siehe auch

  • dirname() - Extrahiert den Verzeichnis-Namen aus einer vollständigen Pfadangabe
  • basename() - Extrahiert den Namen einer Datei aus einer vollständigen Pfadangabe
  • parse_url() - Analysiert einen URL und gibt seine Bestandteile zurück
  • realpath() - Erzeugt einen kanonisch absoluten Pfadnamen


29 BenutzerBeiträge:
- Beiträge aktualisieren...
fabiolimasouto at gmail dot com
14.10.2010 21:53
Sometimes we want to get an array of each component in the pathname associated with the correspondent path to that directory. We need it for creating breadCrumbs and stuff like that. So here it goes:
<?php

/* Function parsePathComponents
    * parse through all path components
    * resolves the cross platform slash issue
    * eliminates extra redundant slashes
    * @return associative array: ComponentName=>CorrespondentPath
*/

/* Array */
function parsePathComponents($path,$endSlash=true,$base=false)
{
 for(
    
$path = trim($path),
    
$slash = strstr(PHP_OS,'WIN') ? '\/' : '/',
    
$retArray = array(),
    
$str = $temp = "",
    
$x = 0;
 
$char = @$path{$x}; $x++)
 {
  if(!
strstr($slash,$char)) $temp .= $char;
  elseif(
$temp){
      
$str .= $temp;
      
$retArray[$temp] = $str.($endSlash ? $slash{0} : '');
      
$str .= $slash{0};
      
$temp = "";
  }
 }
 
$base&&$temp and $retArray[$temp] = $str.$temp;
 return
$retArray;
}

// Testing in WINDOWS
// NOTE: UNIX will return paths with normal slashes

// return array with path names ending with a slash
$path = '/my//stupid//path/to///some/file.php';
$pathComps = parsePathComponents($path);
print_r($pathComps);

//Array ( [my] => my\ [stupid] => my\stupid\ [path] => my\stupid\path\ [to] => my\stupid\path\to\ [some] => my\stupid\path\to\some\ )

$path = 'my/other//path/';
// return paths not ending with slash
print_r(parsePathComponents($path,false));
// Array ( [my] => my [other] => my\other [path] => my\other\path )

$path = 'my//other/path/to///file.php';
// use third argument = true: for capturing the "file.php" base
print_r(parsePathComponents($path,true,true));

//Array ( [my] => my\ [other] => my\other\ [path] => my\other\path\ [to] => my\other\path\to\ [file.php] => my\other\path\to\file.php )

?>
kc8yds at gmail dot com
18.09.2009 11:43
any type of url parse_url can handle this will get the extension of

pathinfo(parse_url('URL GOES HERE',PHP_URL_PATH),PATHINFO_EXTENSION)
jjoss at mail dot ru
4.02.2009 19:15
pathinfo() which can be used with UTF filenames.

<?php
 
function pathinfo_utf($path)
  {
    if (
strpos($path, '/') !== false) $basename = end(explode('/', $path));
    elseif (
strpos($path, '\\') !== false) $basename = end(explode('\\', $path));
    else return
false;
    if (empty(
$basename)) return false;

   
$dirname = substr($path, 0, strlen($path) - strlen($basename) - 1);

    if (
strpos($basename, '.') !== false)
    {
     
$extension = end(explode('.', $path));
     
$filename = substr($basename, 0, strlen($basename) - strlen($extension) - 1);
    }
    else
    {
     
$extension = '';
     
$filename = $basename;
    }

    return array
    (
     
'dirname' => $dirname,
     
'basename' => $basename,
     
'extension' => $extension,
     
'filename' => $filename
   
);
  }
?>
aalaap at gmail dot com
2.02.2009 16:58
Here is a simple function that gets the extension of a file. Simply using PATHINFO_EXTENSION will yield incorrect results if the path contains a query string with dots in the parameter names (for eg. &x.1=2&y.1=5), so this function eliminates the query string first and subsequently runs PATHINFO_EXTENSION on the clean path/url.

<?php
function extension($path) {
 
$qpos = strpos($path, "?");

  if (
$qpos!==false) $path = substr($path, 0, $qpos);
 
 
$extension = pathinfo($path, PATHINFO_EXTENSION);

  return
$extension;
}
?>
php [spat] hm2k.org
13.01.2009 13:27
A little compat for < 5.2

<?php

function pathinfo_filename($file) { //file.name.ext, returns file.name
   
if (defined('PATHINFO_FILENAME')) return pathinfo($file,PATHINFO_FILENAME);
    if (
strstr($file, '.')) return substr($file,0,strrpos($file,'.'));
}

?>
php-manual at spunts dot net
24.12.2008 18:19
For a good example of how platform independent this function is have a look at the different return values that Lostindream and I experienced. Mine is above and Lostindream's is below:

Array
(
    [dirname] => /www/psychicblast/images/1
    [basename] => my three girlfriends.jpg
    [extension] => jpg
)

Array
(
    [dirname] => /www/htdocs
    [basename] => index.html
    [extension] => html
    [filename] => index
)
z
benjaminhill at gmail dot com
3.12.2008 6:18
A warning: this function varies depending on the platform it is being run on.  For example, pathinfo('C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe') will return a different result when run through a winOS PHP platform (local development) vs. a server's UNIX-based OS.  A bit like the Locale settings, but unexpected.
Lostindream at atlas dot cz
19.08.2008 22:43
at example from "qutechie at gmail dot com" you can only replace function 'strpos' with 'strrpos'. (strrpos — Find position of last occurrence of a char in a string)

It's simple. For example:
<?php

function filePath($filePath)
{
 
$fileParts = pathinfo($filePath);

 if(!isset(
$fileParts['filename']))
 {
$fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));}
 
 return
$fileParts;
}
 
$filePath = filePath('/www/htdocs/index.html');
print_r($filePath);
?>

Output will be:
Array
(
    [dirname] => /www/htdocs
    [basename] => index.html
    [extension] => html
    [filename] => index
)
leons87_AT_hotmail_DOT_com
15.08.2008 13:47
qutechie at gmail dot com wrote a fix for support for filename in PHP 4; however it gets it wrong whenever you have a filename with a . in it (so foo.bar.jpg would return foo instead of foo.bar).

A fix would be:
<?php
if(!isset($path_parts['filename'])){
   
$reversed_filename = strrev( $path_parts['basename'] );
   
$path_parts['filename'] = strrev( substr( $reversed_filename, strpos( $reversed_filename, '.' ) + 1 ) );
}
?>

The idea is that you reverse the string and create a substring that starts after the first '.' and then reverse the result.
qutechie at gmail dot com
22.07.2008 3:29
Quick fix for lack of support for 'filename' in php4

<?php
$path_parts
= pathinfo('/www/htdocs/index.html');

echo
$path_parts['dirname'], "\n";
echo
$path_parts['basename'], "\n";
echo
$path_parts['extension'], "\n";
echo
$path_parts['filename'], "\n"; // since PHP 5.2.0

// if php4
             
if(!isset($path_parts['filename'])){
               
$path_parts['filename'] = substr($path_parts['basename'], 0,strpos($path_parts['basename'],'.'));
              }

?>
christian dot reinecke at web dot de
24.02.2008 16:46
if you call pathinfo with a filename in url-style (example.php?with=parameter), make sure you remove the given parameters before, otherwise they will be returned as part of the extension.

extension => php?with=parameter
tom at foo-bar dot co dot uk
30.01.2008 15:48
Note that this function seems to just perform string operations, and will work even on a non-existent path, e.g.

<?php
print_r
(pathinfo('/no/where/file.txt'));
?>

which will output:
Array
(
    [dirname] => /no/where
    [basename] => file.txt
    [extension] => txt
    [filename] => file
)
OakBehringer
28.01.2008 2:47
Building on David Blinco's function, the following will:

1. Return the correct protocol for secure requests (https)
2. Throw an exception for invalid files
3. Ensure the returned url separates directories with forward slashes (David's will not on Windows systems).

function mapPath ($filepath) {
    $realpath = realpath($filepath);
    $dir;
   
    // Verify that the path passed is real and harvest the bottom directory
    if (is_file($realpath)) {
        $dir = dirname($realpath);
    }
    elseif (is_dir($realpath)) {
        $dir = $realpath;
    }
    else {
        throw new Exception('File does not exist: ' . $realpath);
    }

    // Make sure the path is not lower than the server root
    if (strlen($dir) < strlen($_SERVER['DOCUMENT_ROOT']))
        throw new Exception("Cannot create http path below server http root.");
       
    $path = ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . substr($realpath, strlen($_SERVER['DOCUMENT_ROOT']));
   
    if (DIRECTORY_SEPARATOR == '\\')
        $path = str_replace('\\', '/', $path);

    return $path;
}
davidblinco at gmail dot com
26.01.2008 16:27
This function is not perfect, but you can use it to convert a relative path to a URL.
Please email me if you can make any improvements.

<?php
function mapURL($relPath) {
   
$filePathName = realpath($relPath);
   
$filePath = realpath(dirname($relPath));
   
$basePath = realpath($_SERVER['DOCUMENT_ROOT']);
   
   
// can not create URL for directory lower than DOCUMENT_ROOT
   
if (strlen($basePath) > strlen($filePath)) {
        return
'';
    }
   
    return
'http://' . $_SERVER['HTTP_HOST'] . substr($filePathName, strlen($basePath));
}
?>
henrik at not-an-address dot com
21.12.2007 19:23
If you have filename with utf-8 characters, pathinfo will strip them away:

print_r(pathinfo("/mnt/files/飛兒樂團光茫.mp3"));

 .. will display:

Array
(
    [dirname] => /mnt/files
    [basename] => .mp3
    [extension] => mp3
    [filename] =>
)
mrnemesis at ntlworld dot com
19.12.2007 16:22
Note that in PHP 4 (if you're stuck using it), pathinfo only provides dirname, basename, and extension, but not filename. This function will not split a file's stem and extension for you.
anders.jenbo()pc.dk
11.09.2007 23:34
Heres a funciton to get the same results from php 4+ but you will have to call pathinfo_filename() instead of pathinfo().

<?php
if(version_compare(phpversion(), "5.2.0", "<")) {
    function
pathinfo_filename($path) {
       
$temp = pathinfo($path);
        if(
$temp['extension'])
           
$temp['filename'] = substr($temp['basename'],0 ,strlen($temp['basename'])-strlen($temp['extension'])-1);
        return
$temp;
    }
} else {
    function
pathinfo_filename($path) {
        return
pathinfo($path);
    }
}
?>
avi-team at inbox dot lv
15.07.2007 17:14
You shouldn't assign values as it is described in previous post
// wrong:
list( $dirname, $basename, $extension, $filename ) = array_values( pathinfo($file) );

if $file has no extension, you get wrong variable values: $extension would be assigned with 'filename' array element of pathinfo() result, but $filename - would be empty.
phpnet at whoisgregg dot com
30.05.2007 20:01
If you want to easily assign the values returned by pathinfo to separate variable names, list isn't enough. You can use array_values() first to convert the associative array into the indexed array that list() expects:

// throws notices, variables aren't set
list( $dirname, $basename, $extension, $filename ) = pathinfo($file);

// works
list( $dirname, $basename, $extension, $filename ) = array_values( pathinfo($file) );
cochise_chiracahua at hotmail.com
25.11.2005 20:55
Sometimes, it's interessant to get the basename without extension.
So, I appended a new entry 'basenameWE' (Basename Without Extension) to the returned array.

<?php

// pathinfo improved
function pathinfo_im($path) {
   
   
$tab = pathinfo($path);
   
   
$tab["basenameWE"] = substr($tab["basename"],0
   
,strlen($tab["basename"]) - (strlen($tab["extension"]) + 1) );
   
    return
$tab;
}

$my_path = "/var/www/html/example.html";

echo
"<pre>\n";
print_r( pathinfo_im($my_path) );
echo
"</pre>\n";

?>

Out :

Array
(
    [dirname] => /var/www/html
    [basename] => example.html
    [extension] => html
    [basenameWE] => example
)
sgermain at icexnetworks dot com
8.07.2005 20:24
It is true that if you put a directory into pathinfo, usually the extension is empty. But, if the directory name is /www/example.com/ for example, you will have the following output:

Array
(
    [dirname] => /www
    [basename] => example.com
    [extension] => com
)

So, it is the same as a file.
n0dalus
8.02.2005 10:47
If a file has more than one 'file extension' (seperated by periods), the last one will be returned.
For example:
<?php
$pathinfo
= pathinfo('/dir/test.tar.gz');
echo
'Extension: '.$pathinfo['extension'];
?>
will produce:
Extension: gz

and not tar.gz

3.12.2004 13:39
If you want only the file extension, use this:
<?php
$extension
= substr(strrchr($filename, "."), 1);
?>
This is many times faster than using pathinfo() and getting the value from array.
rob at webdimension dot co dot uk
4.10.2004 15:48
Further to my previous post.

This affects servers that run PHP as a cgi module

If you have your own server:
You can use the AcceptPathInfo directive to force the core handler to accept requests with PATH_INFO and thereby restore the ability to use PATH_INFO in server-side includes.

Further information:
http://httpd.apache.org/docs-2.0/mod/core.html#acceptpathinfo
junk at plaino dot com
19.08.2004 15:41
Convert a URL to the local file path and vice versa, convert a local file path to a URL.

// this sets the sytem / or \ :
strstr( PHP_OS, "WIN") ? $slash = "\\" : $slash = "/";

// This is the location of the php file that contains this
// function. Usually this request is made to files/folders
// down the directory structure, so the php file that
// contains these functions is a good "where am i"
// reference point:
$WIMPY_BASE['path']['physical'] = getcwd();
$WIMPY_BASE['path']['www'] = "http://".$_SERVER['HTTP_HOST'];

function url2filepath($theURL){
    global $WIMPY_BASE, $slash;
    $AtheFile = explode ("/", $theURL);
    $theFileName = array_pop($AtheFile);
    $AwimpyPathWWW = explode ("/", $WIMPY_BASE['path']['www']);
    $AtheFilePath = array_values (array_diff ($AtheFile, $AwimpyPathWWW));
    if($AtheFilePath){
        $theFilePath = $slash.implode($slash, $AtheFilePath).$slash.$theFileName;
    } else {
        $theFilePath = implode($slash, $AtheFilePath).$slash.$theFileName;
    }
    return ($WIMPY_BASE['path']['physical'].$theFilePath);
}

function filepath2url ($theFilepath){
    global $WIMPY_BASE, $slash;
    $AtheFile = explode ($slash, $theFilepath);
    $theFileName = array_pop($AtheFile);
    $AwimpyPathFILE = explode ($slash, $WIMPY_BASE['path']['physical']);
    $AtheFilePath = array_values (array_diff ($AtheFile, $AwimpyPathFILE));
    $thFileURL = implode("/", $AtheFilePath)."/".$theFileName;
    return ($WIMPY_BASE['path']['www']."$thFileURL");
}
albertof at deltasoft dot com dot ar
29.05.2002 10:10
This code is to work in index.php/var/var

if(isset($PATH_INFO)) {
      $viewcode = explode('/', $PATH_INFO);
        $num = count($viewcode);
        if($num % 2 == 0) {
            $viewcode[] = '';
            $num++;
        }
        for($i = 1; $i < $num; $i += 2) {

            $$viewcode[$i] = $viewcode[$i+1];

          }
    }
m-symons at home dot com
25.08.2001 4:01
And, of course, to account for the problem noted in the first post whereby calling a directory, not a file, messes with the output of pathinfo(), you can include the following test:

if($pathinfo[extension] == "") {

$deep++;

}

Ooops...sorry for missing that.
m-symons at home dot com
25.08.2001 3:54
Here's a neat wee function to grab the relative path to root (especially useful if you're using mock-directories to pass variables into scripts with mod_rewrite).  The function simply iterates through every occurence of "/" within the REQUEST_URI environment variable, appending "../" to the output for every instance:

<?php

function path_to_root($path) {

   
$pathinfo = pathinfo($path);
   
   
$deep = substr_count($pathinfo[dirname], "/");
   
   
$path_to_root = "./";
   
    for(
$i = 1; $i <= $deep; $i++) {
   
       
$path_to_root .= "../";
       
    }
   
    return
$path_to_root;
}

path_to_root($REQUEST_URI);

?>
mikep at oeone dot com
22.08.2001 19:27
If you run this on a directory, basename is the last directory in the path, dirname is the path before the final directory and extension is empty.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)