代码之家  ›  专栏  ›  技术社区  ›  Paige Ruten

只允许包含PHP文件的最佳方法是什么?

php
  •  11
  • Paige Ruten  · 技术社区  · 16 年前

    我想确保人们不能在URL中键入PHP脚本的名称并运行它。最好的方法是什么?

    我可以在文件中设置一个包含此文件的变量,然后检查文件中包含的变量,但有没有更简单的方法?

    7 回复  |  直到 8 年前
        1
  •  7
  •   UnkwnTech    16 年前

    您可以检查URI并查看是否使用`

    $_SERVER['SCRIPT_FILENAME']
    

    或者您可以将文件移出公用文件夹,这是一个更好的解决方案。

        2
  •  11
  •   nickf    16 年前

    在我介绍的几个开源应用程序中,包括joomla和phpbb,它们在主includes文件中声明一个常量,然后验证每个includes中是否存在该常量:

    // index.php
    require_once 'includes.php';
    
    // includes.php
    define('IN_MY_PROJECT', true);
    include 'myInc.php';
    
    // myInc.php
    defined('IN_MY_PROJECT') || die("No direct access, plsktnxbai");
    
        3
  •  4
  •   Michael Johnson    16 年前

    我一直把所有东西都保存在Web根目录之外,除了可以直接查看的脚本。然后将php配置为在路径中包含脚本目录。典型的设置是:

    appdir
      include
      html

    在php配置中(全局php配置或 .htaccess 文件中 html 目录)添加:

    include_path = ".:/path/to/appdir/include:/usr/share/php"

    或(对于Windows)

    include_path = ".;c:\path\to\appdir\include;c:\php\includes"

    注意这一行可能已经在您的 php.ini 文件,但可能被注释掉,允许默认值工作。它还可能包括其他路径。一定要保留这些。

    如果要将其添加到.htaccess文件,则格式为:

    php_value include_path .:/path/to/appdir/include:/usr/share/php

    最后,您可以通过编程方式添加路径,如下所示:

    $parentPath = dirname(dirname(__FILE__));
    $ourPath = $parentPath . DIRECTORY_SEPARATOR . 'include';
    
    $includePath = ini_get('include_path');
    $includePaths = explode(PATH_SEPARATOR, $includePath);
    // Put our path between 'current directory' and rest of search path
    if ($includePaths[0] == '.') { 
        array_shift($includePaths);
    }
    
    array_unshift($includePaths, '.', $ourPath);
    $includePath = implode(PATH_SEPARATOR, $includePaths);
    ini_set('include_path', $includePath);
    

    (基于工作代码,但已修改,因此未测试)

    这应该在前端文件中运行(例如 index.php )我把它放在一个单独的include文件中,在修改了上面的内容之后,它可以包含在 #include '../includes/prepPath.inc' .

    我已经成功地使用了我在这里展示的所有版本。所使用的特定方法取决于首选项以及如何部署项目。换句话说,如果你不能修改 PHPini 你显然不能用那种方法

        4
  •  0
  •   rg88    16 年前

    Zend框架建议您将文件保存在Web根目录之外,正如Unknwntech所建议的那样。我想说这是最安全和最简单的解决方案。

        5
  •  0
  •   ThoriumBR    16 年前

    从php nuke模块:

    <?php
    if (!eregi("modules.php", $PHP_SELF)) {
       die ("You can't access this file directly...");
    }
    // more code ...
    ?>
    

    用您的文件名替换modules.php,该文件不能直接调用。

        6
  •  0
  •   Kent Boogaart    16 年前

    我经常看到的一种方法是创建一个变量,该变量必须出现在每个包含的文件中,并检查每个包含的第一件事:

    if(!isset($in_prog)){
    exit;
    }
    
        7
  •  0
  •   Tristan Le Gacque    8 年前

    我想最好的办法是把你想放进去的文件放进去。” 包括 “文件夹并将访问权限700放到文件夹中。”