Using PHP basename() Function to Retrieve File Names from Paths
This article explains the PHP basename() function, detailing its syntax, parameters, and behavior, and demonstrates its usage through multiple code examples that extract file names from absolute and relative paths, optionally removing specified suffixes, while noting OS-specific considerations.
In PHP programming, file path operations are common. The basename() function helps quickly obtain the filename part of a path. This article details the function's capabilities and usage, and demonstrates its practical application with code examples.
The basic syntax of basename() is as follows:
string basename ( string $path [, string $suffix ] )Parameter description:
$path : required, represents the file path, which can be relative or absolute.
$suffix : optional, the file extension to be removed.
Functionality:
Retrieves the filename portion of the path.
The following examples demonstrate how to use 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() , which returns the filename index.php and assigns it to $filename , then prints it.
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 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 the suffix from the filename and returns index .
The return value of basename() is a string containing only the filename part of the path. If the path does not contain a filename, the function 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 "/", so be mindful of these differences when using the function.
Summary
In PHP development, the basename() function is highly useful for extracting 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.
Java learning resources
C language learning resources
Frontend learning resources
C++ learning resources
PHP learning resources
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.