2

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  
  }  
}

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

If I understand correctly you want __FILE__.

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

Comments

0

I think you want to use:

_SERVER["PHP_SELF"]

eg:

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

Will

Comments

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

Works on the command line too.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.