CascadiaPHP 2024

pathinfo

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pathinfoRestituisce informazioni su un percorso di file

Descrizione

pathinfo(string $path, int $options = ?): array

pathinfo() restituisce un vettore associativo contenente informazioni riguardo path. Nel vettore vegono riportati i seguenti elementi: dirname, basename e extension.

Si può specificare quali elementi vengano restituiti con parametri opzionali options. E' composto da PATHINFO_DIRNAME, PATHINFO_BASENAME e PATHINFO_EXTENSION. Assume per defalut la restituzione di tutti gli elementi.

Example #1 pathinfo() Example

<?php
$path_parts
= pathinfo('/www/htdocs/index.html');
echo
$path_parts['dirname'], "\n";
echo
$path_parts['basename'], "\n";
echo
$path_parts['extension'], "\n";

?>

Produrrà:

 
 /www/htdocs 
 index.html 
 html 
 

Nota:

Per informazioni su come recuperare il path corrente, leggere la sezione su variabili riservate predefinite.

Vedere anche dirname(), basename(), parse_url() e realpath().

add a note

User Contributed Notes 4 notes

up
41
Lori
5 years ago
Simple example of pathinfo and array destructuring in PHP 7:
<?php
[ 'basename' => $basename, 'dirname' => $dirname ] = pathinfo('/www/htdocs/inc/lib.inc.php');

var_dump($basename, $dirname);

// result:
// string(11) "lib.inc.php"
// string(15) "/www/htdocs/inc"
?>
up
7
urvi
1 year ago
about the path, there are one thing you should note :
On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/). (this explain is from basename() function part https://www.php.net/manual/en/function.basename.php)
example:
<?php
$path
= "https://urvidutta.com /a\b\c\filename.pdf";

echo
pathinfo($pdfUrl, PATHINFO_BASENAME); //get basename
//output
//on window: result is filename.pdf
//on Linux: result is a\b\c\filename.pdf (that is may not your expect)

//so in order to get same result in different system. i will do below first.
$path = str_replace($path, '\\', '/'); //convert '\' to '/'
?>
up
13
Pietro Baricco
12 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
11
n0dalus
19 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
To Top