Skip to content

How to get a file name from a path in PHP?

In this tutorial, you will learn how to get the file name from the path in PHP with examples. You will need to use any one of the following two methods to get the filename from the given path.

  • Using the basename() function
  • Using the pathinfo() Function

Method 1- basename() function:

<?php
  $path = "D:/projects/example-voting-app/docker-compose.yml";
  $file = basename($path).PHP_EOL;         
  print_r($file); // Output: docker-compose.yml
  $file = basename($path, ".yml"); 
  print_r($file) // Ouput: docker-compose
?>

Method 2- pathinfo() function:

<?php
  $path = "D:/projects/example-voting-app/docker-compose.yml";
  echo pathinfo($path, PATHINFO_BASENAME).PHP_EOL; // Output: docker-compose.yml
  echo pathinfo($path, PATHINFO_FILENAME);  //Output:  docker-compose  
  print_r(pathinfo($path));
  /*
  Output: 
  (
    [dirname] => D:/projects/example-voting-app
    [basename] => docker-compose.yml
    [extension] => yml
    [filename] => docker-compose
) */
?>
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments