pathinfo() can return dirname, basename, filename and extension. It works on the path string; it does not verify that the file actually exists.
$path = '/var/www/files/report.csv';
$info = pathinfo($path);
echo $info['dirname'] . '<br>';
echo $info['basename'] . '<br>';
echo $info['filename'] . '<br>';
echo $info['extension'] . '<br>';This example shows the recommended starting pattern. Continue below for variations, explanation and the original practical examples.
<?Php
//$file = $_SERVER["SCRIPT_NAME"]; // Takes the current file name
$file='https://127.0.0.1/t/file/path.php'; // Path is stored in Variable
$path_details=pathinfo($file);
//echo print_r($path_details);
echo $path_details['dirname']; // Output is: <i>https://127.0.0.1/t/file</i>
echo "<br>";
echo $path_details['basename']; // Output is: <i>path.php</i>
echo "<br>";
echo $path_details['extension']; // Output is: <i>php</i>
echo "<br>";
echo $path_details['filename']; // Output is: <i>path</i>
?>
Syntax
pathinfo(path, flags)
path:flags:echo print_r(pathinfo($file,PATHINFO_FILENAME));// output path
Using foreach
$file='https://127.0.0.1/t/file/path.php'; // Path is stored in Variable
$path_details=pathinfo($file);
foreach($path_details as $key => $val) {
echo "$key -> $val <br>";
}
Output
dirname -> https://127.0.0.1/t/file
basename -> path.php
extension -> php
filename -> path
Using *pathinfo()*, we can extract just the file extension from a given file path:
$file = "/var/www/html/index.php";
$info = pathinfo($file);
echo "File extension: " . $info['extension'];
// Outputs: File extension: php
To retrieve the file name without the extension:
$file = "/var/www/html/index.php";
$info = pathinfo($file);
echo "File name: " . $info['filename'];
// Outputs: File name: index
Here’s how to rename a file by adding a timestamp:
$file = "document.pdf";
$info = pathinfo($file);
$new_file = $info['filename'] . "_" . time() . "." . $info['extension'];
echo $new_file;
// Outputs: document_1634567890.pdf
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.