Disable direct access to the PHP include file

In many times it may be needed to include one or more PHP file to other PHP files. We do it so that we don’t have to write the same code again.

But what happened if you access a PHP file that is only created to be included in another PHP file? Most probably you will get some error message depending upon the codes.

Of course, it will not look good if someone accesses those PHP files and gets the error message. You need to find a way so that the error message will be removed.

PHP urlencode And urldecode functions and it’s usage

Read meta description and title tag of a web page using PHP

Another reason for removing the error is because it may be a security issue. From the error messages of directly accessing the PHP include files may contain some information which can be used by a cracker to harm your site.

So, in this post, I am going to show you the code snippets which will prevent your PHP files that are created to be included in other PHP files. Well, after this tutorial users will still be able to access the PHP include files directly, but they will show your own message “Direct access not allowed” instead of showing those error messages.

I am going to discuss two methods now.

Method 1

Put the below PHP code at the top of your PHP include file:

if( count(get_included_files()) == ((version_compare(PHP_VERSION, '5.0.0', '>='))?1:0) )
  echo "Direct access not allowed";

After putting the above code, whenever someone will access the PHP include file directly, it will show the message “Direct access not allowed” and after that, it will exit and the rest of the code will not run which causes for error message.

Method 2

Below is the given code that you need to put at the top of the included file:

  if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) {
  die('Direct access not allowed');

After that, you will no longer see the error messages if you try to access the file directly. it will show “Direct access not allowed” message instead of showing the error message.

Leave a Reply

Your email address will not be published. Required fields are marked *