PHP basename() Function | Get Filename from Path

The PHP basename() function is used to get the file name from the specified path. For example:

<?php
   $path = "C:/Users/DEV/codescracker.com/myfile.txt";
   echo basename($path);
?>

The output of the above PHP example is:

php basename function

And here is the snapshot of the directory and path along with the file used in the above example:

php basename function example

PHP basename() Syntax

The syntax of the basename() function in PHP is:

basename(path, suffix)

The second, or suffix, parameter is optional. This parameter is used when we need to remove the extension of the file so that we only get the file name. For example:

<?php
   $path = "C:/Users/DEV/codescracker.com/myfile.txt";
   echo basename($path, ".txt");
?>

This code defines a variable $path that contains the file path "C:/Users/DEV/codescracker.com/myfile.txt". The path uses forward slashes to separate directories, which is the recommended practice for compatibility across different platforms. The function basename() is then called with two arguments: $path and ".txt." The basename() function parses the path and returns the file name as a string. The second argument, ".txt," instructs the function to remove the ".txt" extension from the file name if it is present.

The output of the above PHP example is:

basename function php

Advantages of the basename() function in PHP

Disadvantages of the basename() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!