How to get the current script running name of the file in PHP

We can get the current file name or the file executing the code by using SCRIPT_NAME. This will give us the path from the server root so the name of the current directory will also be included. Here is the code.
file = $_SERVER["SCRIPT_NAME"];
echo $file;
The above lines will print the present file name along with the directory name. For example if our current file is test.php and it is running inside my_file directory then the output of above code will be.
/my_file/test.php
We will add some more code to the above line to get the only file name from the above code. We will use explode command to break the string by using delimiter “/” .

As the output of this explode command is an array then we will collect the last element of this array to get our file name. Here the index of last element of the array is total element of the array minus one, because the index of the elements start from 0 ( not from one ). So index of the last element of the array = total number of elements – 1

Here is the code to get the last element of the array with the explode command to get the array.
$break = Explode('/', $file);
$pfile = $break[count($break) - 1];
Here $pfile is the variable which will have the value of present file name.

We can use $pfile in different application where current file name is required .

Here is the complete code.
$file = $_SERVER["SCRIPT_NAME"];
    $break = Explode('/', $file);
    $pfile = $break[count($break) - 1]; 

echo $pfile;
The output is here
test.php
Another easy way is to use basename of pathinfo

File Deleting File Checking if file exists before deleting
PHP
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Marcel Burkhard

    08-07-2014

    How about just using the __LINE__ magic constant?

    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer