The basename Function

The basename function returns the trailing name component of the path. The first parameter is the path string, the second (optional) one is the suffix to be stripped from the result. The function works with both UNIX-style and Windows paths.

Syntax

phpbasename(path, [suffix]);

Example

Getting a filename from a full path:

php<?php
  echo basename('/var/www/site/index.html');
?>

Code execution result:

php'index.html'

Example

Getting a filename with the extension removed:

php<?php
  echo basename('/var/www/site/index.html', '.html');
?>

Code execution result:

php'index'

Example

Working with Windows paths:

php<?php
  echo basename('C:\Windows\system32\cmd.exe');
?>

Code execution result:

php'cmd.exe'

Example

Getting a directory name:

php<?php
  echo basename('/var/www/site/');
?>

Code execution result:

php'site'

See Also

  • the dirname function,
    which returns the directory name
  • the pathinfo function,
    which returns information about a path
  • the realpath function,
    which returns the absolute path