PHP inclusion tricks

I just figured out a couple of things in PHP, so I thought I’d share them.

PHP has a useful include statement.  (This is a language construct, not a function, as the PHP documentation makes sure to mention!)  Within one PHP file, you can include another and execute it.

Recently I started wondering: Is it possible for PHP code to know whether it’s being included, as opposed to executed directly?  In a word: Yes.  PHP has myriad predefined variables that hold information about the environment.  In particular, $_SERVER[“PHP_SELF”] holds the relative path of the file being executed.  Here’s some code.

# If our file is http://example.com/php_stuff/php_file.php then our relative path is:
$relative_path = "/php_stuff/php_file.php";
# Note the leading slash. This is how it works on my system; I encourage you to use the useful phpinfo() function to find out how your system works.
# So, above we defined the relative path that we are expecting. Now we test the PHP_SELF variable to see if we've been included.
# (Note, the strcmp function returns a 0 if the strings are identical. I found I had to use this function instead of an operator. Test and see what works for you.)
if (strcmp($relative_path, $SERVER["PHP_SELF"]) == 0)
$included = false;
else
$included = true;
# And now the $included variable holds a value telling us if we've been included.

I’m sure there are other ways to accomplish this, of course.  For example, you could have the including script set a variable; if the variable is not set, the file has not been included.  However, in that case you have to make sure every including script sets the same variable; With my method, the included script has all the information it needs.  The only caveat is that the relative path must contain the current location of the script—if the value is outdated, the script will always think it’s being included.

Responses are currently closed.