Prevent Direct Access to a PHP File – At the Web Server is a Better Idea

PHP - direct access Over the years, I’ve seen many ways to prevent direct access to a PHP files. I’m going to show you some of them. Certain applications have their own way of preventing direct access but it’s totally unnecessary if instructions for doing it at the web server exist. That is, of course, when you have access to the web server. If you do, I’ll show you the easiest and most effective way.

Prevent Direct Access from within PHP Files

This one uses the realpath function:

if ( realpath(__FILE__) === realpath($_SERVER["SCRIPT_FILENAME"]) ) { 
  exit("Direct access not permitted.");
}

This one uses the get-included-files function. Be aware that “1” is correct for PHP5 and above. You shouldn’t be using PHP4 or below anyway. This is the best PHP-driven method I’ve seen:

if ( count( get_included_files() ) == 1 ) {
  exit("Direct access not permitted.");
}

WordPress does it this way because it defines the ABSPATH constant every time WordPress loads:

if (!is_defined('ABSPATH') ) {
  exit('Direct access not permitted.');
}

Some plugin authors use other constants and different messages, but they all do the same thing.

Prevent Direct Access from Nginx and Apache

With Nginx, it’s done like this in the configuration files:

if ($request_uri ~* ^/somefile.php) {
  return 403;
}

Multiple files:

if ( $request_uri ~* ^/(onefile|twofile).php ) {
  return 403;
}

With Apache, it’s done like this with .htaccess files (and can be done at the main configuration level as well):

<FilesMatch "^/somefile.php$">
  Order Deny,Allow
  Deny from all
</FilesMatch>

Multiple files:

<FilesMatch "^/(onefile|twofile).php$">
    Order Deny,Allow
    Deny from all
</FilesMatch>

If you can access a PHP file, you can access a database through it. It’s a huge hit on resources. If you can’t access PHP file, it’s a tiny hit on resources. Which way do you think is best?

I’m sure this can be done with other web servers, like LiteSpeed, but I don’t know how difficult it is to do it.

If you’re doing this on shared hosting, you may not have access to the web server configuration files. Your web server should be configured to allow you to handle configuration files in your web space. If it isn’t, your hosting provider should be able to set that up for you.

Using PHP itself to prevent direct access should be a last resort. Developers add PHP code to prevent access to specific PHP files simply because end-users are sometimes clueless when it comes to web security.

Share this: