basename
Returns the last part of a path — the file name.
Syntax
basename(string $path, string $suffix = ""): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $path | string | The path. |
| $suffix | string | Optional. An ending to cut off. |
Return value
stringThe name of the file or folder.
Examples
The file name with and without the extension:
<?php
echo basename('/var/www/uploads/photo.jpg'), "\n";
echo basename('/var/www/uploads/photo.jpg', '.jpg');Output:
photo.jpg
photoProtection against leaving the folder:
<?php
echo basename('../../secret/config.php');Output:
config.phpNotes
The companion dirname() returns the path without its last part. Both work on the string — the file itself need not exist.
See also
- pathinfo — Splits a path into parts: the folder, the name and the extension.
- file_exists — Checks whether a file or folder exists.
Related recipes
In the tutorial
- Folders and paths — Working with folders in PHP — creating them, listing files, searching by a mask, parts of a path and file information.