ActiveState Code

Recipe 207176: Protect PHP File that must be include


This Section is describe how we can protect php module that can calling in with include function, but is not secure and its have big risk. For the solution is we can make this module file cannot execute or calling when it's not include, the code simple with test file name. Some study case: we hosting in sites that we cannot protection in dir, regulary we add .htacces in folder /inc/ I was putin .htacces so if we calling http://localhost/inc/ is displayed forbidden but if I try if we calling http://localhost/inc/connect-module.php it will be succesfull and maybe some accident will happen here

PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?
### filename: connect-module.php
### this file cannot execute if we are not calling by include function
### by pass section, must be place berfore do anything (on top line)
if(eregi("connect-module.php",$PHP_SELF)) exit(); 


### your code begin below
###............

?>

Comments

  1. 1. At 7:58 p.m. on 20 feb 2004, François Lécolier said:

    Using "Files" Apache directive makes this easier. Warning: This comment may only interest you if your PHP code is running on your own Apache server

    To avoid including code in all your PHP incudes, you may add a suffix your include file names, and then tell Apache to deny access to files having this suffix.

    I use a '.inc.php' suffix for my include files and have the following lines in the Apache configuration file (eg httpd.conf or apache.conf) :

    <Files ~ ".inc.php$">

    Order allow,deny
    
    Deny from all
    

    </Files>

  2. 2. At 8:43 a.m. on 17 may 2005, Derek Harmel said:

    A More Generic Approach. Another solution for preventing access to include files that would not have to be changed on a page-to-page basis is the following:

    if( basename( __FILE__ ) == basename( $_SERVER['PHP_SELF ) )
    {
      exit();
    }
    
  3. 3. At 8:45 a.m. on 17 may 2005, Derek Harmel said:

    A More Generic Approach. Another solution for preventing access to include files that would not have to be changed on a page-to-page basis is the following:

    if( basename( __FILE__ ) == basename( $_SERVER['PHP_SELF'] ) )
    {
      exit();
    }
    
  4. 4. At 1:13 p.m. on 28 sep 2006, Antti Pikkarainen said:

    Another quick method.. Universal check whether file is included or requested via HTTP GET: Or to put it another way: if HTTP_GET contains CURRENT_FILE_NAME exit;

    if(eregi($_SERVER["SCRIPT_NAME"], $_SERVER["REQUEST_URI"]))
    exit;
    

    Seems fool proof to me...?

  5. 5. At 10:45 a.m. on 7 sep 2008, Eddie said:

    Or another way, if your server supports it, is to have your includes above the webroot directory. So if pages are server from /var/www/htdocs, then have your includes be located in /var/www. This way there isn't a way to access those files.

Sign in to comment