pathinfo(): get details of a file path

<?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:
Required path to be parsed.
flags:
Optional PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.
All are returned if not given.
The function pathinfo returns an array.
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

Example 2: Extracting File Extension from a 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

Example 3: Getting File Name Without Extension

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

Use Case: Dynamically Renaming Files

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

File Deleting File Checking if file exists before deleting
PHP
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer