Sometimes you might want to know whether a script is the top level script or whether it has been included. That could be useful if you want to reuse the routines in another script, but you don't want to separate them out. Here's a way that seems to be working for me (for both Apache2 module and CLI versions of PHP) on my Win XP Pro system.
By the way, if __FILE__ is within a function call, its value corresponds to the file it was defined in and not the file that it was called from. Also, I used $script and strtolower instead of realpath because if the script is deleted after inclusion but before realpath is called (which could happen if the test is deferred), then realpath would return empty since it requires an extant file or directory.
Csaba Gabor from Vienna
<?php
if (amIincluded()) return;
function amIincluded() {
$webP = !!$_SERVER['REQUEST_METHOD']; $script = preg_replace('/\//',DIRECTORY_SEPARATOR,
$_SERVER['SCRIPT_FILENAME']);
return ($webP) ? (strtolower(__FILE__)!=strtolower($script)) :
!array_key_exists("_REQUEST", $GLOBALS);
}
?>