How to Use PHP's basename() Function to Extract File Names from Paths
This article explains the PHP basename() function, detailing its syntax, parameters, and behavior across operating systems, and demonstrates its usage through three practical examples that show how to retrieve file names from absolute and relative paths, with and without suffix removal.
In PHP programming, the basename() function provides a quick and convenient way to obtain the file name part of a path. This article introduces the function's capabilities and usage, illustrated with code examples.
The basic syntax of basename() is:
string basename ( string $path [, string $suffix ] )Parameters:
$path: required, the file path, which can be relative or absolute.
$suffix: optional, the file extension to remove.
Functionality:
Returns the file name portion of the 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() , returning "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 "pic.jpg".
Example 3:
$path = "/var/www/html/index.php";
$filename = basename($path, ".php");
echo $filename;Output:
indexIn this case, an additional suffix ".php" is specified, so basename() removes the suffix and returns "index".
The function returns a string containing only the file name part of the path; if no file name exists, it returns ".". Note that results may vary across operating systems because Windows uses "\\" as the path separator, while Linux and macOS use "/".
Summary
In PHP development, the basename() function is highly useful for extracting file names from paths, applicable in file operations, URL handling, and uploads. Mastering this function 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.