How To Get File Name From a Path in PHP Example

Reading Time: 2 minutes
908 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.

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

<?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.

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

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more