Using PHP basename() Function to Extract File Names from Paths
This article introduces PHP's basename() function, explains its syntax and parameters, and provides multiple code examples showing how to extract filenames from absolute and relative paths, including optional suffix removal and cross‑platform considerations.
In PHP programming, handling file paths is common, and the basename() function provides a quick way to retrieve the filename part of a path. This article explains the function’s syntax, parameters, and behavior, and demonstrates its usage with several code examples.
string basename ( string $path [, string $suffix ] )Parameter Description:
$path : required, the file path which can be relative or absolute.
$suffix : optional, a file extension to be removed from the result.
Functionality:
Returns the filename portion of a path.
Below are several examples demonstrating the use of basename() :
Example 1:
$path = "/var/www/html/index.php";
$filename = basename($path);
echo $filename;Output:
index.phpIn this example, the absolute path "/var/www/html/index.php" is passed to basename() , and the returned filename is assigned to $filename , which is then printed, yielding "index.php".
Example 2:
$path = "images/pic.jpg";
$filename = basename($path);
echo $filename;Output:
pic.jpgHere a relative path "images/pic.jpg" is provided, and basename() returns only the filename "pic.jpg".
Example 3:
$path = "/var/www/html/index.php";
$filename = basename($path, ".php");
echo $filename;Output:
indexIn this case an optional suffix ".php" is supplied; basename() removes that suffix from the filename and returns "index".
The function returns a string containing only the filename part of the path. If the path does not contain a filename, it returns ".".
Note that the result of basename() may be affected by the operating system: Windows uses "\\" as the path separator, while Linux and macOS use "/". Therefore, be aware of the appropriate separator when using the function.
Summary
In PHP development, the basename() function is very useful for easily obtaining the filename from a file path. It can be applied in file operations, URL handling, file uploads, and other scenarios, improving development efficiency and code readability when mastered and used flexibly.
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.