<?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