How To Get File Name From a Path in PHP Example

Table of Contents

Share this Article
Reading Time: 3 minutes
417 Views

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.

Learn More –

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

<?php

  $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

Output

data.xml

data

Method #2: Using pathinfo() PHP function

<?php

$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/>";

print_r(pathinfo($path));

Output

data.xml

data

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.

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.

Was this post helpful?

Get PHP Web Development Courses on Offer in just ₹299
Get PHP Web Development Courses on Offer in just ₹299