Master PHP’s basename() Function: Extract Filenames Easily

This article explains PHP's basename() function, covering its syntax, parameters, and practical examples that demonstrate how to extract filenames from both absolute and relative paths, including handling of optional suffix removal and OS-specific considerations.

php Courses
php Courses
php Courses
Master PHP’s basename() Function: Extract Filenames Easily

In PHP programming, the basename() function quickly retrieves the filename part of a path. This article explains its syntax, parameters, functionality, and provides several examples.

Parameter description:

$path

: required, the file path (relative or absolute). $suffix: optional, a file extension to remove.

Functionality:

Returns the filename portion of the path.

Examples:

Example 1

string $path = "/var/www/html/index.php";
$filename = basename($path);
echo $filename;

Output:

index.php

Example 2

string $path = "images/pic.jpg";
$filename = basename($path);
echo $filename;

Output:

pic.jpg

Example 3 (using suffix)

string $path = "/var/www/html/index.php";
$filename = basename($path, ".php");
echo $filename;

Output: index The 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().

Conclusion

The basename() function is useful for extracting filenames from paths in PHP, applicable in file operations, URLs, uploads, and more, improving development efficiency and code readability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingPHPFile Pathbasename
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.