Getting the name of file in PHP

How can I get the name of a file in in PHP? What I want to do is have a function take a string of a filename and then do some stuff if it's actually on the page.

function onThisPageFunction(fileNameFromFunction)  
{  
  if(onThisPage == fileNameFromFunction)  
  {  
    do stuff  
  }  
}
Asked By: Paul Sheldrake
||

Answer #1:

There are two variables that will give you file names.

eg: you call /test/test1.php as the url and test1.php includes test2.php.

__FILE__ will give you the current file of the executing code, in this case it will return "test2.php"

$_SERVER['PHP_SELF'] will give you the full url of the original call, in this case "/test/test1.php"

Note that you can use the basename() function to get just the filename from a path.

Answered By: Eric Goodwin

Answer #2:

If I understand correctly you want __FILE__.

Ref: http://php.net/manual/en/language.constants.predefined.php

Answered By: activout.se

Answer #3:

I think you want to use:

_SERVER["PHP_SELF"]

eg:

    if (isset($_SERVER["PHP_SELF"]) AND  ($_SERVER["PHP_SELF"] == 'foo')){
echo 'do stuff';
}

Will

Answered By: William Macdonald

Answer #4:

if (realpath($_SERVER['SCRIPT_NAME']) === __FILE__) {
    echo "Called directly";
}

Works on the command line too.

Answered By: troelskn

Answer #5:

Thanks for your responses. This is what ended up doing the job for me.

function menuStrikethrough($pageName)
    {
        // get the name of the page we're on
        $fileName = basename($_SERVER['PHP_SELF']);

        // if fileName equals pageName then output css to show a strikethrough
        if($fileName == $pageName)
        {
            echo ' style="text-decoration:line-through" ';
        }
    }

I found ____FILE____ didn't work for me because I wrote this function in an included file.

The basename tip came in handy.

Thanks for all the help!

Answered By: Paul Sheldrake
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles