• Posted on March 31, 2014

PHP Prevent Include Direct Access

It’s good practice to limit where your website visitors can go so they don’t get into trouble or cause problems with your site. Although, problems should occur when they directly access a file they are not supposed to, sometimes you can’t help it.

Below is a very simple way to prevent your users from directly accessing important system files for your website.

What you have to first do is identity a file that all pages use and include. Most sites now have a single “index.php” file which is used to parse the URL and then load the appropriate content. If that’s the case with your website, you will want to use index.php in this tutorial. If your website is using a more classic approach of having each webpage as a different file, you can use a file you include on every site such as “header.php”, but keep in mind that this file will not be protected like the others. Also note that this has to be the first file you include.

The Code

The code is a simple if statement that will check for a variable we set. If the variable isn’t set, the website didn’t request that file, the user direclty accessed it.

Post the following code in your “header.php” or “index.php” file at the very top, or at least before you include any files.

define('SITE_LOADED',true);

Now in all of the other files on your webserver, at the very top of the file you will want to add the follow.

if(!defined('SITE_LOADED')) {
	die();
}

This will kill the requested page if accessed directly. It’s a great way to prevent parts of a template to be loaded without first having your script process the data for the site.