PHP -- get current file name

lomn75

Purple Ace
Joined
Jun 26, 2000
Messages
6,613
OK, here's the goal:

I want to prevent direct access to some include files with some config variables. I can't guarantee the files will sit outside of the webserver's document root.

What I'm thinking is to compare the $_SERVER["SCRIPT_NAME"] (that is, the URI) against the filename of the include file, and if there's a match, that's a direct view of the include file so make a call to die() before the variables are set.

The approach works fine except that I'm not sure how to determine the file name of the include file automatically (I'd prefer not to have to type it in on each file). Is there anything like a $this handler for the filesystem or something? The problem with $_SERVER["SCRIPT_FILENAME"] is that it returns the originating file rather than the current file. That's fine for the disallow case but doesn't work for legal includes/requires.
 
use __FILE__

eg...
PHP:
----->CUT<---- start inc.php
<?php
echo "I am inc.php:" . __FILE__;
?>
----->CUT<---- end inc.php


----->CUT<---- start too.php
<?php
include("inc.php");
echo "<br> I am too.php: " . __FILE__;
?>
----->CUT<---- end too.php
 
I've also added basename(__FILE__) to my bag of tricks now, much better than reinventing the wheel as I'd been doing. User comments in the manual are nice.

While on the topic, though, I see the suggestion of using
Code:
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
  exit;
}
but I can't figure out why realpath() is needed. I don't see how either __FILE__ or the $_SERVER parameter would ever return things like "../../whatever", which is what realpath() seems to be intended to circumvent.

Any ideas on scenarios that would make realpath() necessary?

//edit: I'm currently using
Code:
if(strtr(__FILE__, "\\", "/") == $_SERVER["SCRIPT_FILENAME"])
to get Win/*nix compatibility
 
Back
Top