Master PHP’s pathinfo(): Extract Directories, Filenames, and Extensions Easily
This guide explains how PHP's pathinfo() function can dissect a file path into directory, base name, extension, and filename without extension, showing syntax, option constants, practical code examples, and typical output for common development tasks.
Summary
In PHP development, the pathinfo() function provides a convenient way to dissect a file path into its constituent parts such as directory name, base name, extension, and filename without extension.
The basic syntax is pathinfo($path, $options), where $path is the file path string and $options is an optional constant that determines which component to return. If $options is omitted, the function returns an associative array containing all components.
Common option constants: PATHINFO_DIRNAME – returns the directory portion of the path. PATHINFO_BASENAME – returns the file name with extension. PATHINFO_EXTENSION – returns only the file extension. PATHINFO_FILENAME – returns the file name without its extension.
Example usage:
// Define a sample path
$path = "/home/user/www/example.php";
// Directory name
$dirname = pathinfo($path, PATHINFO_DIRNAME);
echo "Directory: " . $dirname . "
";
// Base name
$basename = pathinfo($path, PATHINFO_BASENAME);
echo "File name: " . $basename . "
";
// Extension
$extension = pathinfo($path, PATHINFO_EXTENSION);
echo "Extension: " . $extension . "
";
// Filename without extension
$filename = pathinfo($path, PATHINFO_FILENAME);
echo "Filename (no ext): " . $filename . "
";Running the script produces:
Directory: /home/user/www
File name: example.php
Extension: php
Filename (no ext): exampleUsing pathinfo() simplifies tasks such as handling file uploads, generating dynamic file names, or performing any operation that requires knowledge of a file’s directory, name, or type.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
