Backend Development 3 min read

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:

<code>string basename ( string $path [, string $suffix ] )</code>

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:

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

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

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

backend-developmentPHPstring-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

login 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.