我如何清理我的包含声明?

时间:2009-11-25 19:25:53

标签: php security include

如何清除此内容,以便用户无法将网页拉出本地域?

<?php
 if(!empty($_GET['page']))
 {
  include($_GET['page']);
 }
 else
 {
  include('home.php');
 }
?>

4 个答案:

答案 0 :(得分:12)

最安全的方法是将您的网页列入白名单:

$page = 'home.php';

$allowedPages = array('one.php', 'two.php', ...);

if (!empty($_GET['page']) && in_array($_GET['page'], $allowedPages))
    $page = $_GET['page'];

include $page;

答案 1 :(得分:2)


// get the absolute file name of the page we want to see
$page = realpath($_GET['page']);

// get the directory in which pages are
$mydir = dirname(__FILE__);

// see if the included page is inside this allowed dir
if ($page === false || substr($page, 0, strlen($mydir) != $mydir) {
 die('go away hacker');
} else {
 include $page;
}

答案 2 :(得分:0)

未经测试。我只是快速地写了它,但它应该工作(我希望),它肯定会为你提供一个从哪里开始的基础。

define('DEFAULT_PAGE', 'home.php');
define('ALLOWED_PAGES_EXPRESSION', '^[\/]+\.php$|^[\/]+\.html$');

function ValidateRequestedPage($p)
{
    $errors_found = False;

        // Make sure this isn't someone trying to reference directories absolutely.
    if (preg_match('^\/.+$', $p))
    {
        $errors_found = True;
    }

        // Disable access to hidden files (IE, .htaccess), and parent directory.
    if (preg_match('^\..+$', $p))
    {
        $errors_found = True;
    }


        // This shouldn't be needed for secure servers, but test for remote includes just in case...
    if (preg_match('.+\:\/\/.+', $p))
    {
        $errors_found = True;
    }

    if (!preg_match(ALLOWED_PAGES_EXPRESSION, $p))
    {
        $errors_found = True;
    }

    return !$errors_found;
}

if (!isset($_GET['page'])) { $page = DEFAULT_PAGE; }
else { $page = $_GET['page']; }

if ( !ValidateRequestedPage($page) )
{
    /* This is called when an error has occured on the page check. You probably
       want to show a 404 here instead of returning False. */
    return False;
}

// This suggests that a valid page is being used.
require_once($page);

答案 3 :(得分:0)

只需使用switch语句。

检查是否设置了$ _GET var,然后通过案例运行它并将默认设置转到home.php