PHP | basename( ) Function

The basename() function in PHP is an inbuilt function which is used to return the base name of a file if the path of the file is provided as a parameter to the basename() function.

Syntax:

string basename ( $path , $suffix )

Parameters: The basename() function in PHP accepts two parameters which are path and suffix.



  1. $path: This parameter is of string type and is mandatory. It specifies the path of the file.
  2. $suffix: It is an optional parameter which hides the extension of a file if it ends with a suffix.

Return Value: This function returns the basename of the file whose path has been given as a parameter by the user.

Errors And Exception:

  1. The basename() function doesn’t recognise path components such as ‘..’ .
  2. The basename() function operates on the input string provided by the user and is unaware of the actual filesystem.
  3. Both slashes, forward slash (/) and backslash (\) are used as directory separator character on a windows platform whereas it is just a forward slash (/) in other environments.

Examples:

Input : $path = "user01/home/documents/geeksforgeeks.php",
Output : geeksforgeeks.php

Input :  $path = "user01/home/documents/geeksforgeeks.php",
         $suffix = ".php"
Output : geeksforgeeks

Below programs illustrate the basename() function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$path = "user01/home/documents/geeksforgeeks.php";
  
// basename() function to show
// filename along with extension
echo basename($path);
  
?>

chevron_right


Output:

geeksforgeeks.php

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$path = "user01/home/documents/geeksforgeeks.php";
  
// basename() function to show the
// filename while hiding the extension
echo basename($path, ".php");
  
?>

chevron_right


Output:

geeksforgeeks

Reference:
http://php.net/manual/en/function.basename.php



My Personal Notes arrow_drop_up

I am a technology enthusiast who has a keen interest in programming I am pursuing Engineering in Computer Science from GEU, Dehradun I like to unwind by watching movies and English sitcomsI have a keen interest in music

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.