清理$ _GET参数以避免XSS和其他攻击

时间:2009-10-19 09:19:48

标签: php sanitization

我在php中有一个包含()的网站,用于将内容嵌入到模板中。要加载的页面在get参数中给出,我将“.php”添加到参数的末尾并包含该页面。我需要做一些安全检查以避免XSS或其他东西(不是mysql注入,因为我们没有数据库)。我想出的是以下内容。

$page = $_GET['page'];

if(!strpos(strtolower($page), 'http') || !strpos($page, '/') ||
    !strpos($page, '\\') || !strpos($page, '..')) {
        //append ".php" to $page and include the page

我还能做些什么来进一步消毒我的意见吗?

3 个答案:

答案 0 :(得分:30)

$page = preg_replace('/[^-a-zA-Z0-9_]/', '', $_GET['page']);

可能是消毒的最快方法,这将采取任何措施,并确保它只包含字母,数字,下划线或破折号。

答案 1 :(得分:7)

不要“消毒” - 攻击特定于数据的使用,而不是来源。改为输出它们时转义值。另请参阅我对What’s the best method for sanitizing user input with PHP?

的回答

答案 2 :(得分:4)

定义源代码中的明确页面列表,然后使用它来检查输入。是的,这是更多的工作,但它很清楚什么是允许的,什么是不允许的。例如:

$AVAILABLE_PAGES = array('home', 'news',  ...);
$AVAILABLE_PAGES = array_fill_keys($AVAILABLE_PAGES, 1);

$page = $_GET['page'];
if (!$AVAILABLE_PAGES[$page]) {
   header("HTTP/1.0 404 Not Found");
   die('Page not found.');
}

include "pages/$page.php";
相关问题