
PHP basename() Function
In PHP, basename()
is a built-in function used to extract the base name of a file or directory path. It returns the last component of the path, effectively removing the parent directory components.
Here’s the syntax of the basename()
function:
string basename(string $path[, string $suffix]);
Parameters:
$path
: The file or directory path from which to extract the base name.$suffix
(optional): If provided, this string will be removed from the end of the base name. This can be useful if you want to remove a specific file extension or suffix.
Return value:
- The
basename()
function returns a string representing the base name of the provided path.
Examples:
- Basic Usage:
$path = "/home/user/documents/file.txt";
$baseName = basename($path);
echo $baseName; // Output: "file.txt"
- Removing a Suffix:
$path = "/home/user/documents/file.txt";
$suffix = ".txt";
$baseName = basename($path, $suffix);
echo $baseName; // Output: "file"
In the first example, we pass a file path to the basename()
function, and it returns the base name of the file (“file.txt”).
In the second example, we provide a file path and a suffix (“.txt”) as arguments to the basename()
function. It removes the suffix from the end of the base name and returns “file” as the result.
The basename()
function is commonly used for processing file paths, especially when you want to extract the name of a file from its full path or remove a specific extension from the file name.