PHP Tutorial - PHP basename() function






Definition

To get the filename part of a path, you can use the basename() function.

Syntax

PHP basename() function has the following syntax.

basename(filePath,extension)

Parameter

PHP basename() function takes a path as its first parameter and, optionally, an extension as its second parameter.

Return

The return value is the name of the file without the directory information.

If the filename has the same extension as specified, the extension is taken off also.

Example

Get the filename part of a path


<?PHP
      $filename = basename("/home/somefile.txt");
      echo $filename . "\n";
      $filename = basename("/home/somefile.txt", ".php");
      echo $filename . "\n";
      $filename = basename("/home/somefile.txt", ".txt");
      echo $filename . "\n";
?>

The code above generates the following result.