tags:

views:

153

answers:

6

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  
  }  
}
+3  A: 

If I understand correctly you want __FILE__.

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

divideandconquer.se
+6  A: 

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.

Eric Goodwin
A: 

I think you want to use:

_SERVER["PHP_SELF"]

eg:

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

Will

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

Works on the command line too.

troelskn
A: 

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!

Paul Sheldrake