Returns the final name component of a filesystem path.
What Is basename() in PHP?
Returns the final name component of a filesystem path.
Its syntax is:
basename(string $path, string $suffix = ""): string
Parameters:
$path— Accepted as string; required argument.$suffix— Accepted as string; optional default "".
Return type: string. basename() operates on text and does not validate a filesystem path. Never rely on it alone for safe upload filenames or access control.
Availability: Available in standard PHP.
Example 1: Basic Usage
<?php
echo basename("/data/reports/sales.csv");
Output:
sales.csv
Basename() operates on text and does not validate a filesystem path. Never rely on it alone for safe upload filenames or access control.
Example 2: A Different Input
<?php
echo basename("/data/reports/sales.csv", ".csv");
Output:
sales
Basename() operates on text and does not validate a filesystem path. Never rely on it alone for safe upload filenames or access control.
Practical Example: Applying It in a Program
<?php
$uploads = ["/tmp/photo.png", "/tmp/report.pdf"];
foreach ($uploads as $upload) { echo basename($upload) . PHP_EOL; }
Output:
photo.png
report.pdf
Basename() operates on text and does not validate a filesystem path. Never rely on it alone for safe upload filenames or access control.
Important Behavior and Edge Cases
- Key behavior: basename() operates on text and does not validate a filesystem path. Never rely on it alone for safe upload filenames or access control.
- Environment: Available in standard PHP.
Comparison With Related Functions
| Function | Purpose |
|---|---|
basename() | returns the final name component of a filesystem path. |
dirname() | dirname() returns the parent path; basename() returns its last filename or directory component. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: basename() operates on text and does not validate a filesystem path | basename() operates on text and does not validate a filesystem path. Never rely on it alone for safe upload filenames or access control. |
Key Takeaways
- returns the final name component of a filesystem path.
- basename() operates on text and does not validate a filesystem path. Never rely on it alone for safe upload filenames or access control.
- Available in standard PHP.
Summary: basename() operates on text and does not validate a filesystem path. Never rely on it alone for safe upload filenames or access control.