How to get file name of a path using PHP?

To show the file name of URL or path we have 2 methods:

Method 1: With basename() function:

The path to a file is passed as a parameter to the basename() function, which returns the file’s base name.

Path is a required field that tells what path should be checked. The suffix is an optional field that tells you what kind of file it is.

This file extension is in the file name, the file extension won’t show.

Syntax: $file_name = basename(path, suffix);

<?php
  $url_path = "https://www.phpcodenmore.com/index.php";
  
  $file_name1 = basename($url_path);
  $file_name2 = basename($url_path, ".php");
  
  // Show file name with extension
  echo $file_name1 . "\n";
  
  // Show file name without extension
  echo $file_name2;
?>

Output:
index.php
index

Method 2: With pathinfo() function:

The pathinfo() function is a built-in function that returns information about a path using an associative array or a string.

It will create an array with the parts of the path we want to use.

Syntax: $file_name = pathinfo(path);

<?php
  // Path under pathinfo function
  $url_path = pathinfo('https://www.phpcodenmore.com/index.php');
  // Show the file name
  echo $url_path['basename'], "\n";
?>

Output:
index.php