I came across this issue while working on my Facebook application. I didn’t want people to be able to view these PHP files locally because they are included in other files. There are a few ways to do this, you can use an htaccess file to block Apache from loading the file when accessed directly. Another way to do it is to have PHP check a $_server variable and die if it returns true. Here is the code
if ('filename.php' == basename($_SERVER['SCRIPT_FILENAME']))
die (’what you want to display’);
So what you need to do is change filename.php to the name of the actual file. Ex. If the filename is includeme.php that is what goes where filename.php is. You can change “what you want to display” to the text you want displayed when that file is directly accessed. If you really want to you can add in logging to the if statement, you’ll have to look that up on Google (there are many ways to implement that).
So how does it work?
$_SERVER['SCRIPT_FILENAME'] returns the absolute file name of the current executing script. basename strips everything except the filename, so if $_SERVER['SCRIPT_FILENAME'] returns /home/public_html/filename.php then basename would change that to filename.php. So what the if statement is doing is saying if this string is equal to this (if you didn’t already know == means equal to. One = just means equals ($test = ‘hello world!’; means that $test is the string hello world!)). The die comes in if the if statement is true. You don’t need braces because they fall on the same line, there is only one ; in that statement. If you were to add more lines to execute if the if statement is true then you would need braces and it would look something like this
if ('filename.php' == basename($_SERVER['SCRIPT_FILENAME']))
{
// you can add things to do inside these braces
die (’what you want to display’);
}
I just thought I would mention that the way you do the braces is personal preference. I put them on new lines because it is easier for me to read but you could also do them like this
if ('filename.php' == basename($_SERVER['SCRIPT_FILENAME'])) {
// you can add things to do inside these braces
die (’what you want to display’);
}
and this
if ('filename.php' == basename($_SERVER['SCRIPT_FILENAME'])) {
// you can add things to do inside these braces
die (’what you want to display’); }
You will get the same result either way because, well I was going to say the compiler but in PHP’s case the Preprocessor, white space between the braces doesn’t matter. Hopefully you found that or other things I brought up interesting.

No Comments on "Blocking Direct Access to a PHP File"