Using PHP pathinfo() Function to Retrieve File Path Information
This article explains how the PHP pathinfo() function can extract directory name, base name, extension, and filename from a file path, demonstrates its syntax and options, and provides practical code examples with expected output for web development tasks.
In web development we often need to manipulate files, such as obtaining file information or paths. PHP offers many functions for these tasks, and the pathinfo() function is especially useful because it can easily extract various pieces of information from a file path.
The basic syntax of pathinfo() is:
pathinfo($path, $options);$path is the file path, and $options is an optional parameter that controls the output. The function returns an array containing the different parts of the path. Below are the most common options.
1. PATHINFO_DIRNAME : returns the directory portion of the path. 2. PATHINFO_BASENAME : returns the file name with extension. 3. PATHINFO_EXTENSION : returns the file extension. 4. PATHINFO_FILENAME : returns the file name without the extension.
Here are some code examples that demonstrate how to use pathinfo() :
// Get the directory part of the path
$path = "/home/user/www/example.php";
$dirname = pathinfo($path, PATHINFO_DIRNAME);
echo "Directory: " . $dirname . "\n";
// Get the base name (file name with extension)
$basename = pathinfo($path, PATHINFO_BASENAME);
echo "File name: " . $basename . "\n";
// Get the file extension
$extension = pathinfo($path, PATHINFO_EXTENSION);
echo "Extension: " . $extension . "\n";
// Get the file name without extension
$filename = pathinfo($path, PATHINFO_FILENAME);
echo "File name (no extension): " . $filename . "\n";Running the above code produces the following output:
Directory: /home/user/www
File name: example.php
Extension: php
File name (no extension): exampleBy using the pathinfo() function, developers can easily obtain the directory, file name, extension, and filename without extension from a path, which is frequently needed in file upload and processing scenarios.
Summary:
The pathinfo() function is a convenient PHP utility for extracting various file path components.
PATHINFO_DIRNAME retrieves the directory part of a path.
PATHINFO_BASENAME retrieves the file name with its extension.
PATHINFO_EXTENSION retrieves the file’s extension.
PATHINFO_FILENAME retrieves the file name without the extension.
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.