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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1587695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:11:39  来源:igfitidea点击:

Sanitize $_GET parameters to avoid XSS and other attacks

phpsanitization

提问by Federico klez Culloca

I have a website in php that does include() to embed the content into a template. The page to load is given in a get parameter, I add ".php" to the end of the parameter and include that page. I need to do some security check to avoid XSS or other stuff (not mysql injection since we do not have a database). What I've come up with is the following.

我有一个 php 网站,它使用 include() 将内容嵌入到模板中。要加载的页面在 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

Is there any other thing I can do to furtherly sanitize my input?

我还能做些什么来进一步清理我的输入?

回答by Mez

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

Is probably the quickest way to sanitize this, this will take anything and make sure that it only contains letters, numbers, underscores or dashes.

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

回答by troelskn

Don't "sanitize" - Attacks are specific to the use of data, not the source. Escape values as you output them instead. See also my answer to What's the best method for sanitizing user input with PHP?

不要“清理” - 攻击特定于数据的使用,而不是源。在输出时转义值。另请参阅我对使用 PHP 清理用户输入的最佳方法是什么的回答

回答by Luká? Lalinsky

Define an explicit list of pages you have in your source code and then use it to check the input. Yes, it's more work, but it makes it very clear what is allowed and what is not. For example:

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

$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";