这个文件是包含文件吗?

Is there any way to determine if the current file is the "root" file (requested by apache, or ran via the CLI) or if it is an included file?

basename($_SERVER['SCRIPT_FILENAME']) != basename(__FILE__) 

Would work, but it only works based on filenames, not the whole path, so kinda hacky. I'd prefer if there was a nicer, and more elegent way to do this.


Bit of context

I'm writing a PHP 5.4+ API framework named Scaffold, which is extremely useful for the api first methodology. The current issue is, is that many people who write an api first application, use their api via a class in the application.

$user = Scaffold::get('/users/nathaniel');

A nice way to do this, is if that was the actual api, rather than subsequently sending a web request to the server. That way, you avoid the overhead of the HTTP protocol.

I have a pretty good idea on how to do that, but the problem is, I need to know if I should send the response to the browser (encoded and all) or wait for a manual call of Scaffold::request (or any of it's aliases, Scaffold::get being just one of them.

The way I've decided to do this, is to check if the root file of the application (the file usually requested via apache) was actually requested, or was included by a different file.

I found something that works by myself. This is PHP 5.4+ only (because of function back referencing)

get_included_files()[0] === __FILE__

A common way to check for inclusion is to define a constant in the script file that should be the entry point, and then let the files that should be included check for the existence of the constant. If it's not defined, then the file was executed directly instead of included.

Another way, maybe slower to execute but doesn't require outside constants to be defined, would be to check the call stack with debug_backtrace().

Another 'hacky' way to do it would be to set a variable say $is_included, and in the included file check if $is_included is set.

Demonstrated below.

Including file (Any.php):

$is_included = true;
include('File.php');

File.php:

if(!isset($is_included)){
    die('Direct Access not allowed.');
}
// And the code goes here..

If I am not wrong, codeigniter uses something like this to protect cmd line access directly.