Wednesday, October 29, 2008

How to get the file name of the current loaded script using 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;

Article Source

0 comments:

Your Ad Here
Reader's kind attention....The articles contained in this blog can be taken from other web sites, as the main intention of this blog is to let people get all sides of the web technologies under the single roof..so if any one finds duplication or copy of your articles in this blog and if you want that to be removed from this ..kindly inform me and i will remove it...alternatively if you want me to link back to your site with the article...that can also be done...

Thanks,
Webnology Blog Administrator
 

blogger templates