Secure Include Files In PHP

Including files in any PHP program is a very common practice and is nothing out of the ordinary. However, problems can occur when a user navigates to a script file that has a function, but is meant to be included as part of the larger program. For example, if your system includes a file to delete something then if that file is run by itself then there is a chance that it will delete everything.

Of course there are other factors like database access, global variables and sessions that would cause any script to simply error and not cause a problem. However, it is good practice to make sure that any include file is only run when it is included, and not when it is run on it's own.

The following little snipped of code can be placed at the top of any include files to make sure that it can't be run outside of an include. The file in this example would be called "test.php".

if ( preg_match("/test\.php/", $_SERVER['PHP_SELF']) ) {
  exit;
}

If the current filename (found with $_SERVER["PHP_SELF"]) is not test.php then the script simply exits. If the file is included then this $_SERVER will be the name of the file that includes this file.

Another step can be added to make sure that a file is only included by the correct file. The following snipped of code will cause a script to exit if the $_SERVER["PHP_SELF"] variable is not search.php.

if ( !preg_match("/search\.php/", $_SERVER['PHP_SELF']) ) {
  exit;
}

Comments

Another way would be to assign a constant in the main index file, and check whether the constant is available in any sub scripts using: Index.php
define("INDEX",true);
subindex.php
if(!defined("INDEX")) {
	die("You cannot view this file directly!");
}
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.