PHP Prevent Include Direct Access

GeekThis remains completely ad-free with zero trackers for your convenience and privacy. If you would like to support the site, please consider giving a small contribution at Buy Me a Coffee.

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.


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')) {

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.

Related Posts

Prevent Sending HTTP Referer Headers from Your Website

Learn how to prevent your site from sending HTTP referer headers to external websites that you link to with these three different methods.

Process Incoming Mail with PHP Script with Exim

Learn how to process incoming e-mails to your server with a PHP or other script.

PHP - Check if Production or Sandbox

Use PHP to check of your site is on your development server or uploaded to the production server.

Custom Style RSS Feed

Customize the look and feel of your WordPress RSS feed by adding a stylesheet to your RSS XML feed.