【问题标题】:Preventing direct access to php files防止直接访问 php 文件
【发布时间】:2011-08-03 17:34:35
【问题描述】:

这是我的文件结构示例。

/index.php
/inc
/inc/file1.php
/inc/file2.php
/inc/file3.php
/search.php

index.php 包括() file1.php、file2.php 和 file3.php。 我希望它们只能由 index.php 访问。

最优雅的解决方案是什么?

谢谢

【问题讨论】:

    标签: php apache


    【解决方案1】:

    将它们放在文档根目录之外:

    /documentroot/index.php
    /inc/file1.php
    /inc/file2.php
    /inc/file3.php
    

    因此,无论如何都无法直接访问它们。

    【讨论】:

    • 如果 apache 和 .htaccess 是允许的,则在 /inc 中放入一个 .htaccess 文件,其中包含以下行:Order allow,deny & Deny from all
    【解决方案2】:

    在 index.php 中你可以像这样定义一个常量:

    define('RESTRICTED',1);
    

    然后在你的其他页面中,你把它放在<?php之后

    if(!defined('RESTRICTED'))exit('No direct script access allowed!');
    

    当直接访问其他页面时,上面的代码看到 RESTRICTED 尚未设置,因此它将退出。

    【讨论】:

      【解决方案3】:

      制作一个 .htaccess 文件并将其放入 inc 文件夹中

      <Files .htaccess>
      order allow,deny
      deny from all
      </Files>
      
      <Files *.php>
      order allow,deny
      deny from all
      </Files>
      

      或者把它放在你想拒绝的文件的顶部

      if(strrchr($_SERVER['PHP_SELF'],'/')=='/file_name.php'){die;} // not good for ajax include
      

      【讨论】:

        猜你喜欢
        • 2016-03-04
        • 2010-09-29
        • 2012-09-16
        • 1970-01-01
        • 1970-01-01
        • 2019-09-20
        • 1970-01-01
        相关资源
        最近更新 更多