Reputation: 1717
I have a PHP file that can be include'd() in various places inside another page. I want to know whether it has been included inside a function. How can I do this? Thanks.
Upvotes: 0
Views: 835
Reputation: 412
You can check if the file is in the array returned by get_included_files(). (Note that list elements are full pathnames.) To see if inclusion occurred during a particular function call, check get_included_files before and after the function call.
Upvotes: 1
Reputation: 2987
There's a function called debug_backtrace()
that will return the current call stack as an array. It feels like a somewhat ugly solution but it'll probably work for most cases:
$allowedFunctions = array('include', 'include_once', 'require', 'require_once');
foreach (debug_backtrace() as $call) {
// ignore calls to include/require
if (isset($call['function']) && !in_array($call['function'], $allowedFunctions)) {
echo 'File has not been included in the top scope.';
exit;
}
}
Upvotes: 2
Reputation: 2995
You can set a variable in the included file and check for that variable in your functions:
include.php:
$included = true;
anotherfile.php:
function whatever() {
global $included;
if (isset($included)) {
// It has been included.
}
}
whatever();
Upvotes: 1