Using PHP basename() Function to Extract File Names from Paths
This article explains the PHP basename() function, covering its syntax, parameters, and behavior, and provides three practical code examples demonstrating how to extract file names from absolute and relative paths and how to remove a specified suffix, while noting OS-specific considerations.
In PHP programming, manipulating file paths is common, and the basename() function provides a quick way to retrieve the filename portion of a path. This article details the function’s capabilities, usage, and demonstrates its application through code examples.
The basic syntax is:
string basename ( string $path [, string $suffix ] )Parameters:
$path : required, the file path (relative or absolute).
$suffix : optional, a file extension to be removed.
Functionality: it returns the filename part of the given path.
Example 1 – extracting the filename from an absolute path:
$path = "/var/www/html/index.php";
$filename = basename($path);
echo $filename; // outputs: index.phpExample 2 – extracting from a relative path:
$path = "images/pic.jpg";
$filename = basename($path);
echo $filename; // outputs: pic.jpgExample 3 – removing a suffix:
$path = "/var/www/html/index.php";
$filename = basename($path, ".php");
echo $filename; // outputs: indexIf the path does not contain a filename, basename() returns ".". The function’s behavior may vary across operating systems because Windows uses "\\" as the directory separator, while Linux and macOS use "/".
In summary, the basename() function is a useful tool for obtaining file names from paths in PHP, applicable in file handling, URL processing, and upload scenarios, and mastering it can improve development efficiency and code readability.
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.