How to Use PHP's basename() Function to Extract File Names from Paths

This article explains the PHP basename() function, detailing its syntax, parameters, and behavior across operating systems, and demonstrates its usage through three practical examples that show how to retrieve file names from absolute and relative paths, with and without suffix removal.

php Courses
php Courses
php Courses
How to Use PHP's basename() Function to Extract File Names from Paths

In PHP programming, the basename() function provides a quick and convenient way to obtain the file name part of a path. This article introduces the function's capabilities and usage, illustrated with code examples.

The basic syntax of basename() is:

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

Parameters:

$path: required, the file path, which can be relative or absolute.

$suffix: optional, the file extension to remove.

Functionality:

Returns the file name portion of the path.

Below are several examples demonstrating the use of basename():

Example 1:

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

Output: index.php In this example, the absolute path "/var/www/html/index.php" is passed to basename(), returning "index.php".

Example 2:

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

Output: pic.jpg Here a relative path "images/pic.jpg" is provided, and basename() returns "pic.jpg".

Example 3:

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

Output: index In this case, an additional suffix ".php" is specified, so basename() removes the suffix and returns "index".

The function returns a string containing only the file name part of the path; if no file name exists, it returns ".". Note that results may vary across operating systems because Windows uses "\\" as the path separator, while Linux and macOS use "/".

Summary

In PHP development, the basename() function is highly useful for extracting file names from paths, applicable in file operations, URL handling, and uploads. Mastering this function can improve 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.

Backendstring-functionsbasenamefile-path
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.