Backend Development 3 min read

Using PHP basename() Function to Extract File Names from Paths

This article explains the PHP basename() function, covering its syntax, parameters, and behavior, and provides three practical code examples demonstrating how to extract file names from absolute and relative paths and how to remove a specified suffix, while noting OS-specific considerations.

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

In PHP programming, manipulating file paths is common, and the basename() function provides a quick way to retrieve the filename portion of a path. This article details the function’s capabilities, usage, and demonstrates its application through code examples.

The basic syntax is:

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

Parameters:

$path : required, the file path (relative or absolute).

$suffix : optional, a file extension to be removed.

Functionality: it returns the filename part of the given path.

Example 1 – extracting the filename from an absolute path:

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

Example 2 – extracting from a relative path:

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

Example 3 – removing a suffix:

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

If the path does not contain a filename, basename() returns ".". The function’s behavior may vary across operating systems because Windows uses "\\" as the directory separator, while Linux and macOS use "/".

In summary, the basename() function is a useful tool for obtaining file names from paths in PHP, applicable in file handling, URL processing, and upload scenarios, and mastering it can improve development efficiency and code readability.

backend developmentPHPfile pathbasenamestring function
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.