Backend Development 4 min read

Using PHP basename() Function to Extract Filenames from Paths

This article introduces PHP's basename() function, explains its syntax and parameters, and demonstrates its usage through three code examples that show extracting filenames from absolute and relative paths and removing a specified suffix, while also noting OS-specific path separator considerations.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP basename() Function to Extract Filenames from Paths

In PHP programming, it is often necessary to manipulate file paths, and the basename() function provides a quick and convenient way to obtain the filename part of a path. This article explains the functionality and usage of basename() 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, a file extension to be removed.

Functionality:

Returns the filename portion of the given 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() , the returned filename is assigned to $filename , and echoed, resulting in "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 the filename "pic.jpg".

Example 3:

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

Output:

index

In this case an optional suffix ".php" is specified; basename() removes the suffix from the filename and returns "index".

The function returns a string containing only the filename part of the path. If the path does not contain a filename, it returns ".".

Note that the result of basename() may be affected by the operating system: Windows uses "\\" as the path separator, while Linux and macOS use "/". Therefore, be mindful of the separator when using the function.

Summary

In PHP development, the basename() function is highly useful for extracting the filename from file paths, and it can be applied in file operations, URL handling, file uploads, and other scenarios to improve development efficiency and code readability.

php入门教程之一周学会PHP

扫描二维码免费领取学习资料

Backend DevelopmentPHPphp-functionsfile pathbasenamefilename extraction
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.