What's the best way to only allow a PHP file to be included?

In a few of the open source applications I've poked around in, including Joomla and PHPBB, they declare a constant in the main includes file, and then verify that constant exists in each of the includes:

// index.php
require_once 'includes.php';

// includes.php
define('IN_MY_PROJECT', true);
include 'myInc.php';

// myInc.php
defined('IN_MY_PROJECT') || die("No direct access, plsktnxbai");

You could check the URI and see if that file is being called with `

$_SERVER['SCRIPT_FILENAME']

or you could move the file outside the public folder, this is a better solution.


I have long kept everything except directly viewable scripts outside the web root. Then configure PHP to include your script directory in the path. A typical set up would be:

appdir
  include
  html

In the PHP config (either the global PHP config or in a .htaccess file in the html directory) add this:

include_path = ".:/path/to/appdir/include:/usr/share/php"

or (for Windows)

include_path = ".;c:\path\to\appdir\include;c:\php\includes"

Note that this line is probably already in your php.ini file, but may be commented out allowing the defaults to work. It might also include other paths. Be sure to keep those, as well.

If you are adding it to a .htaccess file, the format is:

php_value include_path .:/path/to/appdir/include:/usr/share/php

Finally, you can add the path programatically with something like this:

$parentPath = dirname(dirname(__FILE__));
$ourPath = $parentPath . DIRECTORY_SEPARATOR . 'include';

$includePath = ini_get('include_path');
$includePaths = explode(PATH_SEPARATOR, $includePath);
// Put our path between 'current directory' and rest of search path
if ($includePaths[0] == '.') { 
    array_shift($includePaths);
}

array_unshift($includePaths, '.', $ourPath);
$includePath = implode(PATH_SEPARATOR, $includePaths);
ini_set('include_path', $includePath);

(Based on working code, but modified, so untested)

This should be run in your frontend file (e.g. index.php). I put it in a separate include file which, after modifying the above, can be included with something like #include '../includes/prepPath.inc'.

I've used all the versions I've presented here with success. The particular method used depends on preferences, and how the project will be deployed. In other words, if you can't modify php.ini, you obviously can't use that method

Tags:

Php