Skip to content

Instantly share code, notes, and snippets.

@runspired
Last active December 15, 2015 18:09
Show Gist options
  • Save runspired/5302060 to your computer and use it in GitHub Desktop.
Save runspired/5302060 to your computer and use it in GitHub Desktop.
3 Methods of determining whether a PHP script is executing as an included file.
<?php
/*
One of the more common PHP questions I've encountered is how to determine whether the currently executing
script were included by another script or called directly. Often this question is coupled with AJAX / API
security. While none of the three methods below should be used to consider an AJAX or API request valid,
they will absolutely tell you whether the script was included.
*/
//Method 1 : define a constant in the parent script, check for it in the possibly included script
#======= Main.php ==========
define( 'INTERNAL_REQUEST' , true );
#====== Other.php ==========
$isIncludedFile = defined( 'INTERNAL_REQUEST');
/*
The drawback of method 1 is that you'll only know for certain that the file were included as long as every
time you include it somewhere you also make sure to define INTERNAL_REQUEST. With lots of possibly even
dynamic includes, this gets messy fast. It only takes forgetting to define INTERNAL_REQUEST one time somewhere
to mess everything up, and you'll probably have no idea where to look.
*/
// Method 2 : use $_SERVER and __FILE__ constants
#====== Other.php ==========
$isIncludedFile = ($_SERVER['SCRIPT_FILENAME'] == __FILE__ );
/*
Method 2 is the best method to use of the three presented here. It only goes wrong when you're utilizing the CLI,
so if you know you will be using the CLI, skip on to Method 3. Make sure you use the server var SCRIPT_FILENAME
and not the var PHP_SELF, which will have the wrong capitalization and won't include the server root path.
*/
// Method 3 : user get_included_files() and __FILE__
#====== Other.php ==========
$includes = get_included_files();
$isIncludedFile = ($includes[0] != __FILE__ );
/*
Method 3 works because the originally called script is also the first included script in the array
returned by get_included_files(). So by checking that we aren't that script we know we were included.
The drawback to method 3 is that compared to method 2 making the function call for get_included_files()
is expensive.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment