The pathinfo Function
The pathinfo
function returns an array with information about a file path. We pass a string with the path as the first parameter, and a flag as the second parameter, indicating which specific path component to return.
Syntax
pathinfo(string $path, int $flags = PATHINFO_ALL);
Flags
Flag | Description | Returned Element |
---|---|---|
PATHINFO_DIRNAME |
Returns only the file directory | dirname |
PATHINFO_BASENAME |
Returns only the filename (with extension) | basename |
PATHINFO_EXTENSION |
Returns only the file extension | extension |
PATHINFO_FILENAME |
Returns only the filename (without extension) | filename |
Example
Get all information about the path:
<?php
$res = pathinfo('/var/www/index.php');
print_r($res);
?>
Code execution result:
[
'dirname' => '/var/www',
'basename' => 'index.php',
'extension' => 'php',
'filename' => 'index'
]
Example
Get only the filename:
<?php
echo pathinfo('/var/www/index.php', PATHINFO_FILENAME);
?>
Code execution result:
'index'
Example
Get only the file extension:
<?php
echo pathinfo('/var/www/index.php', PATHINFO_EXTENSION);
?>
Code execution result:
'php'
Example
Get only the filename with extension:
<?php
echo pathinfo('/var/www/index.php', PATHINFO_BASENAME);
?>
Code execution result:
'index.php'
Example
Get only the directory:
<?php
echo pathinfo('/var/www/index.php', PATHINFO_DIRNAME);
?>
Code execution result:
'/var/www'