Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

basename

Returns the last part of a path — the file name.

Syntax

basename(string $path, string $suffix = ""): string

Parameters

ParameterTypeDescription
$pathstringThe path.
$suffixstringOptional. 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
photo

Protection against leaving the folder:

<?php
 
echo basename('../../secret/config.php');

Output:

config.php

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.