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
}
}
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.
If I understand correctly you want __FILE__
.
Ref: http://php.net/manual/en/language.constants.predefined.php
I think you want to use:
_SERVER["PHP_SELF"]
eg:
if (isset($_SERVER["PHP_SELF"]) AND ($_SERVER["PHP_SELF"] == 'foo')){
echo 'do stuff';
}
Will
if (realpath($_SERVER['SCRIPT_NAME']) === __FILE__) {
echo "Called directly";
}
Works on the command line too.
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!