PHP basename() Function: Syntax, Parameters, Return Value, Examples, and Notes

The article explains the PHP basename() function, detailing its syntax, required and optional parameters, return value, practical examples, special handling of directory paths and suffixes, and important usage notes for both Windows and Unix environments.

php Courses
php Courses
php Courses
PHP basename() Function: Syntax, Parameters, Return Value, Examples, and Notes

PHP function basename() is used to obtain the filename portion of a given path.

Basic syntax:

string basename ( string $path [, string $suffix ] )

Parameter description:

$path

: required, the path from which to extract the filename. $suffix: optional, a file extension to be removed from the result.

Return value:

Returns the filename part of the provided path.

Example:

$path = '/dir1/dir2/file.txt';
 echo basename($path); // output: file.txt

$suffix = '.txt';
 echo basename($path, $suffix); // output: file

If $path contains directory components, basename() ignores them and returns only the filename; if $path ends with a slash, an empty string is returned.

When the optional $suffix parameter is provided, basename() removes that suffix from the filename.

Notes:

basename()

does not verify whether the file exists; it merely processes the path string.

The function does not handle query strings in URLs; it returns only the filename portion.

It works correctly with both Windows and Unix style paths.

Summary:

basename()

is a widely used PHP function for extracting the filename from a path, offering a simple and effective way to handle filename‑related operations.

PHP learning recommendations:

Vue3+Laravel8+Uniapp Beginner to Real‑World Development Tutorial

Vue3+TP6+API Social E‑commerce System Development Course

Swoole From Beginner to Advanced Recommended Course

Workerman+TP6 Real‑time Chat System Limited‑Time Offer

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.

PHPString FunctionsFile 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.