note 50561 deleted from language.constants.predefined by googleguy
| From: | googleguy@php.net | Date: | Tue, 22 Oct 2013 10:16:03 +0000 |
| Subject: | note 50561 deleted from language.constants.predefined by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-196955@lists.php.net to get a copy of this message | ||
Note Submitter: csaba at alum dot mit dot edu
----
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; // if we're included we only want function defs
function amIincluded() {
// returns true/false depending on whether the currently
// executing script is included or not
// Don't put this function in an include file (duh)!
$webP = !!$_SERVER['REQUEST_METHOD']; // a web request?
$script = preg_replace('/\//',DIRECTORY_SEPARATOR,
$_SERVER['SCRIPT_FILENAME']);
return ($webP) ? (strtolower(__FILE__)!=strtolower($script)) :
!array_key_exists("_REQUEST", $GLOBALS);
}
?>