PHP Australia Conference 2015

pathinfo

(PHP 4 >= 4.0.3, PHP 5)

pathinfoRetorna informações sobre um caminho de arquivo

Descrição

mixed pathinfo ( string $path [, int $options ] )

pathinfo() retorna um array associativo contendo inforamações sobre o caminho em path.

Parâmetros

path

O caminho sendo verificado.

options

Você pode especificar quais elementos são retornados com o parâmetro opcional options. Ele é composto de PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION e PATHINFO_FILENAME. O padrão é retornar todos os elementos.

Valor Retornado

Os seguintes elementos do array associativo são retornados: dirname, basename, extension (se alguma) e filename.

Se options for utilizada, esta função retornará uma string se todos os elementos não forem solicitados.

Changelog

Versão Descrição
5.2.0 A constante PATHINFO_FILENAME foi adicionada.

Exemplos

Exemplo #1 Exemplo de pathinfo()

<?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"// desde o PHP 5.2.0
?>

O exemplo acima irá imprimir:

/www/htdocs
index.html
html
index

Notas

Nota:

Para informações de como resgatar informações do caminho atual, leia a seção de varíaveis reservadas pré-definidas.

Veja Também

  • dirname() - Retorna o componente diretório de um caminho/path
  • basename() - Retorna a parte nome do arquivo do caminho/path
  • parse_url() - Interpreta uma URL e retorna os seus componentes
  • realpath() - Retorna o path absoluto canonicalizado

add a note add a note

User Contributed Notes 26 notes

up
4
kc8yds at gmail dot com
5 years ago
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)
up
7
Anonymous
9 years ago
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.
up
2
rob at webdimension dot co dot uk
9 years ago
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
up
3
n0dalus
9 years ago
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
up
4
Pietro Baricco
2 years ago
Use this function in place of pathinfo to make it work with UTF-8 encoded file names too

<?php
function mb_pathinfo($filepath) {
   
preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im',$filepath,$m);
    if(
$m[1]) $ret['dirname']=$m[1];
    if(
$m[2]) $ret['basename']=$m[2];
    if(
$m[5]) $ret['extension']=$m[5];
    if(
$m[3]) $ret['filename']=$m[3];
    return
$ret;
}
?>
up
3
krkbpk at gmail dot com RamaKrishna Kothamasu
1 year ago
//pathinfo function example
<?php
//passing single argument
echo "<pre>";
print_r(pathinfo("/home/ramki/ramki.pdf"));
echo
"</pre>";
//passing two agruments
$path=array(PATHINFO_DIRNAME,PATHINFO_BASENAME,PATHINFO_EXTENSION,PATHINFO_FILENAME);
foreach (
$path as $value)
echo
"<pre>".pathinfo("/home/ramki/ramki.pdf",$value)."</pre>";
?>
//output
/*
Array
(
    [dirname] => /home/ramki
    [basename] => ramki.pdf
    [extension] => pdf
    [filename] => ramki
)
/home/ramki
ramki.pdf
pdf
ramki
*/
up
2
henrik at not-an-address dot com
6 years ago
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] =>
)
up
1
benjaminhill at gmail dot com
5 years ago
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.
up
3
phpnet at whoisgregg dot com
7 years ago
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) );
up
1
avi-team at inbox dot lv
7 years ago
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.
up
1
aalaap at gmail dot com
5 years ago
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;
}
?>
up
1
tom at foo-bar dot co dot uk
6 years ago
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
)
up
2
cochise_chiracahua at hotmail.com
8 years ago
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
)
up
2
m-symons at home dot com
13 years ago
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);

?>
up
1
albertof at deltasoft dot com dot ar
12 years ago
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];

          }
    }
up
0
Lostindream at atlas dot cz
6 years ago
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
)
up
0
qutechie at gmail dot com
6 years ago
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'],'.'));
              }

?>
up
0
christian dot reinecke at web dot de
6 years ago
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
up
0
davidblinco at gmail dot com
6 years ago
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));
}
?>
up
0
mrnemesis at ntlworld dot com
6 years ago
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.
up
-1
leons87_AT_hotmail_DOT_com
6 years ago
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.
up
-2
admin at torntech dot com
3 years ago
pathinfo will return null if 0 or null is specified for the option argument.
So you'll need to define it's value manually if the option field is omitted, to provide the default functionality.

<?php

   
public function getFileInfo($source = null, $option = null){
        if(!
$option){
           
//1 + 2 + 4
           
$option = PATHINFO_DIRNAME + PATHINFO_BASENAME + PATHINFO_EXTENSION;
            if(
defined('PATHINFO_FILENAME'))
               
$option += PATHINFO_FILENAME; //8
       
}
        return
pathinfo($source, $option);
    }

   
$obj->getFileInfo("/test/file/someFile.txt");
?>
up
-1
php [spat] hm2k.org
5 years ago
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,'.'));
}

?>
up
-2
jjoss at mail dot ru
5 years ago
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
   
);
  }
?>
up
-4
php-manual at spunts dot net
5 years ago
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
up
-3
Jordan Doyle
1 year ago
It's worth nothing that pathinfo returns foo/index.php for the directory when dealing with URLs like foo/index.php/bar
To Top