Thursday, December 11, 2025
HomeLanguagesHow to get file name from a path in PHP ?

How to get file name from a path in PHP ?

In this article, we will see how to get the file name from the path in PHP, along with understanding its implementation through the examples. We have given the full path & we need to find the file name from the file path. For this, we will following below 2 methods:

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

Input : path = /testweb/var/www/mywebsite/htdocs/home.php
Output : home.php

Input : path = /testweb/var/www/mywebsite/htdocs/abc.txt
Output : abc.txt

We will understand both functions with the help of examples.

Method 1: Using basename() function:

The basename() function is an inbuilt function that returns the base name of a file if the path of the file is provided as a parameter to the basename() function. 

Syntax:

$filename = basename(path, suffix);

The path is a required field that specifies the path which is to be checked. The suffix is an optional field that specifies a file extension. If the filename has this file extension, the file extension will not show.

Example: This example describes the use of the basename() function that returns the base name of the file.

PHP




<?php
  $path = "/testweb/var/www/mywebsite/htdocs/home.php";
  
  $file1 = basename($path);
  $file2 = basename($path, ".php");
  
  // Show filename with file extension
  echo $file1 . "\n";
  
  // Show filename without file extension
  echo $file2;
?>


Output:

home.php
home

Method 2: Using pathinfo() function:

The pathinfo() is an inbuilt function that is used to return information about a path using an associative array or a string ie., It will create an array with the parts of the path we want to use.

Syntax:

$filename = pathinfo(path);

Example: This example explains the pathinfo() function that will return information about a path. Here, we will use $filename[‘basename’], when we want to access the file name.

PHP




<?php
  // Path of the file stored under pathinfo
  $myFile = pathinfo('/usr/admin/config/test.php');
  
  // Show the file name
  echo $myFile['basename'], "\n";
?>


Output:

test.php
RELATED ARTICLES

Most Popular

Dominic
32440 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6811 POSTS0 COMMENTS
Nicole Veronica
11950 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12023 POSTS0 COMMENTS
Shaida Kate Naidoo
6943 POSTS0 COMMENTS
Ted Musemwa
7195 POSTS0 COMMENTS
Thapelo Manthata
6889 POSTS0 COMMENTS
Umr Jansen
6880 POSTS0 COMMENTS