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.

php Courses
php Courses
php Courses
Master PHP’s pathinfo(): Extract Directories, Filenames, and Extensions Easily

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): example

Using 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.

backendFilesystemphp-functionsFile Pathpathinfo
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.