In web development, it's common to work with file paths to extract information such as filenames, extensions, or directory structures. PHP offers many built-in functions to handle these tasks, and one particularly useful function is pathinfo().
pathinfo($path, $options);
$path: Required parameter representing the file path to be parsed.
$options: Optional parameter to specify which part of the path to return (directory, filename, etc.).
By default, the function returns an associative array containing:
dirname: Directory portion of the path
basename: Filename including extension
extension: File extension
filename: Filename without extension
You can use the following constants to specify the part of the path you want:
PATHINFO_DIRNAME: Returns the directory name.
PATHINFO_BASENAME: Returns the filename including extension.
PATHINFO_EXTENSION: Returns the file extension.
PATHINFO_FILENAME: Returns the filename without extension.
Here's an example demonstrating how to extract file information using pathinfo():
<?php // Example file path $path = "/home/user/www/example.php"; // Get directory part $dirname = pathinfo($path, PATHINFO_DIRNAME); echo "Directory: " . $dirname . "\n"; // Get filename with extension $basename = pathinfo($path, PATHINFO_BASENAME); echo "Filename: " . $basename . "\n"; // Get extension $extension = pathinfo($path, PATHINFO_EXTENSION); echo "Extension: " . $extension . "\n"; // Get filename without extension $filename = pathinfo($path, PATHINFO_FILENAME); echo "Filename (without extension): " . $filename . "\n"; ?>
Running the above code will output:
Directory: /home/user/www Filename: example.php Extension: php Filename (without extension): example
In practice, pathinfo() is commonly used for:
Handling file uploads and file path processing;
Determining file type or extension;
Extracting filenames for renaming or storage;
Automatically generating file download links.
To summarize:
pathinfo() is a powerful PHP function for extracting path information;
It provides flexible constants to retrieve specific parts;
Easy to use and greatly improves efficiency in file handling tasks.