How to get file name from a path in PHP?

Given full path, find file name in the path.

Input : path = /testweb/var/www/mywebsite/htdocs/home.php
Output : home.php

Input : path = /testweb/var/www/mywebsite/htdocs/abc.txt
Output : abc.txt



1. Using basename():

Syntax:

$filename = basename(path, suffix);

Path is a required field. It specifies the path to check.
Suffix is a optional field. It specifies a file extension. If the filename has this file extension, the file extension will not show.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!--PHP code to get file name-->
<!--from path name-->
<?php
$path = "/testweb/var/www/mywebsite/htdocs/home.php";
  
$file1 = basename($path);
$file2 = basename($path, ".php");
  
//Show filename with file extension
echo $file1 . "\n";
  
//Show filename without file extension
echo $file2;
?>

chevron_right


Output:

home.php
home

2. Using pathinfo():
Also we can use the function pathinfo() which creates an array with the parts of the path we want to use.

Syntax:

$filename = pathinfo(path);

when we want to access the file name we will use $filename[‘basename’].

filter_none

edit
close

play_arrow

link
brightness_4
code

<!--PHP code to get file name-->
<!--from path name-->
<?php
    //Path of the file stored under pathinfo
    $myFile = pathinfo('/usr/admin/config/test.php');
  
    //Show the file name
    echo $myFile['basename'], "\n";
?>

chevron_right


Output:

test.php


My Personal Notes arrow_drop_up


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.



Improved By : Akanksha_Rai



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.