How to prevent XSS attacks in PHP? [duplicate]

2019-09-22 23:45发布

This question already has an answer here:

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?

1条回答
狗以群分
2楼-- · 2019-09-22 23:51

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.

Example:

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

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.

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

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

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.

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.

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

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

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

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

查看更多
登录 后发表回答