How To Get File Name From a Path in PHP Example

Table of Contents

Share this Article
Reading Time: 2 minutes

Inside this article we will see the concept i.e How To Get File Name From a Path in PHP Example. Article contains the classified information about PHP basename() and pathinfo() functions.

Sometimes when you work, you need the filename from any specific path. So, this tutorial will be helpful for you for this. Tutorial is super easy to understand and implement it in your code as well.

Read More: Laravel How To Disable Primary Key Auto Increment in Model

Let’s get started.

Application Programming

Create a folder say path-filename in your localhost directory. Create a file index.php into it.

We have several methods to get the filename from a file path. Here, we will see two standard methods to get in very easier way.

Method #1: Using basename() PHP function


  $path = "S:/projects/mysample-app/data.xml";
  $file = basename($path).PHP_EOL;         
  print_r($file); // Output: data.xml

  echo "<br/>";

  $file = basename($path, ".xml"); 
  print_r($file); // Ouput: data




Method #2: Using pathinfo() PHP function


$path = "S:/projects/mysample-app/data.xml";
echo pathinfo($path, PATHINFO_BASENAME) . PHP_EOL; // Output: data.xml

echo "<br/>"
echo pathinfo($path, PATHINFO_FILENAME);  //Output:  data
echo "<br/>";





Array ( [dirname] => S:/projects/mysample-app [basename] => data.xml [extension] => xml [filename] => data )

We hope this article helped you to learn How To Get File Name From a Path in PHP Example in a very detailed way.

Read More: Laravel How To Get Array of Ids From Eloquent Model

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.