Master PHP’s basename() Function: Extract Filenames from Paths Easily
This guide explains PHP’s basename() function, detailing its syntax, parameters, and practical examples that show how to retrieve file names from absolute or relative paths, handle suffix removal, and consider OS-specific path separators.
Function Overview
The basename() function in PHP quickly returns the filename portion of a given path. It accepts a required $path argument (absolute or relative) and an optional $suffix to strip a specific file extension.
Syntax
string basename ( string $path [, string $suffix ] )Parameters
$path: Required. The file path, which can be absolute or relative. $suffix: Optional. A suffix (usually a file extension) that will be removed from the returned filename.
Functionality
Returns the filename part of the path.
Examples
Example 1: Basic usage
$path = "/var/www/html/index.php";
$filename = basename($path);
echo $filename;Output: index.php This extracts "index.php" from the absolute path.
Example 2: Relative path
$path = "images/pic.jpg";
$filename = basename($path);
echo $filename;Output: pic.jpg The function correctly returns the filename from a relative path.
Example 3: Removing a suffix
$path = "/var/www/html/index.php";
$filename = basename($path, ".php");
echo $filename;Output: index By providing the optional .php suffix, basename() strips it, returning only "index".
Return Value and Edge Cases
The function returns a string containing the filename. If the path does not contain a filename, it returns ".". Note that path separators differ across operating systems: Windows uses backslashes ("\\"), while Linux and macOS use forward slashes ("/"); ensure the correct separator is used when calling basename().
Conclusion
In PHP development, basename() is a handy utility for extracting filenames from paths, useful in file handling, URL processing, and upload scenarios. Mastering its parameters and OS-specific considerations can improve code efficiency and readability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
