Extract Filename from Path Using PHP basename

This article explains how to use the native PHP basename() function to extract just the filename from a complete file path. You will learn the basic syntax of the function, how to strip file extensions, and how to handle different operating system path formats.

The simplest way to get a filename from a full path in PHP is by passing the path string as the first argument to the basename() function. This function strips away all leading directory information and returns only the final component of the path.

Basic Usage

Here is a straightforward example of how to extract a filename with its extension:

<?php
$filePath = "/var/www/html/uploads/document.pdf";

// Extract the filename
$fileName = basename($filePath);

echo $fileName; 
// Output: document.pdf
?>

Removing the File Extension

If you need to extract the filename without its extension, you can pass the extension as the optional second parameter to the basename() function. If the file ends with that specific extension, it will be omitted from the returned string.

<?php
$filePath = "/var/www/html/uploads/document.pdf";

// Extract the filename without the .pdf extension
$fileNameWithoutExtension = basename($filePath, ".pdf");

echo $fileNameWithoutExtension; 
// Output: document
?>

Handling Dynamic Extensions

If you do not know the file extension beforehand but still want to remove it using basename(), you can combine it with the pathinfo() function to dynamically determine the extension:

<?php
$filePath = "/var/www/html/images/avatar.png";

// Get the extension dynamically
$extension = "." . pathinfo($filePath, PATHINFO_EXTENSION);

// Strip the extension
$fileName = basename($filePath, $extension);

echo $fileName; 
// Output: avatar

Cross-Platform Compatibility

The basename() function is platform-aware. On Windows systems, it recognizes both the forward slash (/) and backslash (\) as directory separators. On Linux and macOS systems, it recognizes the forward slash (/).

<?php
// Windows path example
$windowsPath = "C:\\Users\\Admin\\Documents\\report.docx";

echo basename($windowsPath); 
// Output: report.docx
?>