Friday, October 24, 2025
HomeLanguagesHow to get the current file name using PHP script ?

How to get the current file name using PHP script ?

In this article, we will learn how to get the current filename using PHP.

 
Input : c:/xampp/htdocs/project/home.php
Output : project/home.php

Input : c:/xampp/htdocs/project/abc.txt
Output : project/abc.txt

Sometimes, we need to get the current file name with the directory name in which our page is stored for different purposes. Since we are using PHP, we can easily get the current file name or directory name of the current page by using $_SERVER[‘SCRIPT_NAME’].

Using $_SERVER[‘SCRIPT_NAME’]: $_SERVER is an array of stored information such as headers, paths, and script locations. These entries are created by the webserver. There is no other way that every web server will provide any of this information.

Syntax: ‘SCRIPT_NAME’ gives the path from the root to include the name of the directory.

  1. To get the current file name. We use
    $currentPage= $_SERVER['SCRIPT_NAME'];
  2. To show the current file name. We use
    echo $currentPage;

PHP code: The following is the complete code to get the current file name with the directory name.

PHP




<?php 
    
// To Get the Current Filename.
$currentPage= $_SERVER['SCRIPT_NAME'];
  
// To Get the directory name in 
// which file is stored.
$currentPage = substr($currentPage, 1);
  
// To Show the Current Filename on Page.
echo $currentPage
  
?>


Output:

   project/home.php

 In this code, substr() PHP function is used to extract the part of string from $currentPage variable string. 

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS