Master PHP’s basename() Function: Quick Ways to Extract Filenames
This article explains the PHP basename() function, covering its syntax, parameters, and practical usage with clear code examples that demonstrate how to extract filenames from both absolute and relative paths, including handling of optional suffix removal.
In PHP programming, handling file paths is common. The basename() function helps quickly retrieve the filename part of a path. This article explains its syntax, parameters, functionality, and provides several code examples.
Parameters
$path: required, the file path (relative or absolute). $suffix: optional, a file extension to remove.
Functionality
Returns the filename portion of a path.
Examples:
Example 1:
$path = "/var/www/html/index.php";
$filename = basename($path);
echo $filename;Output:
index.phpExample 2:
$path = "images/pic.jpg";
$filename = basename($path);
echo $filename;Output:
pic.jpgExample 3 (using suffix):
$path = "/var/www/html/index.php";
$filename = basename($path, ".php");
echo $filename;Output:
indexThe function returns a string containing only the filename. If no filename exists, it returns ".". Note that path separators differ between Windows (\\) and Unix-like systems (/), so be aware of OS differences when using basename().
Summary
In PHP development, basename() is a practical tool for extracting filenames from paths, useful in file operations, web links, and uploads. Mastering it can improve development efficiency and code 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.
