Secure Include Files In PHP

8th July 2008 - 2 minutes read time

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".

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

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.

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

Comments

Permalink
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.phpdefine("INDEX",true);subindex.php
  1. if(!defined("INDEX")) {
  2. die("You cannot view this file directly!");
  3. }

Jamie (Tue, 07/08/2008 - 09:35)

Add new comment

The content of this field is kept private and will not be shown publicly.