XSS attack principle and how PHP can prevent XSS attacks
XSS, also known as CSS, is short for Cross-site scripting (XSS) attacks. XSS attacks are similar to SQL injection attacks and are common vulnerabilities in Web programs. XSS is a passive and used for client-side attacks, therefore, it is easy to ignore its dangers. The principle is that attackers input (pass in) malicious HTML code to a website with an XSS vulnerability. When a user browses the website, the HTML code is automatically executed to attack the website. For example, attackers can steal user Cookie information, break the Page Structure, and redirect to other websites.
Theoretically, as long as there is a form that can provide input, and no security filtering or incomplete filtering is performed, there may be an XSS vulnerability. The following are some of the simplest and most common malicious characters in XSS input:
1. XSS input usually contains JavaScript scripts, such as a pop-up malicious warning box: <script> alert ("XSS"); </script> 2.XSS input may also be an HTML code segment, for example: (1 ). <meta http-equiv = "refresh" content = "0;"> (2 ). link embedded in other websites <iframe src = http: // xxxx width = 250 height = 250> </iframe> except for inputting XSS attack characters through normal channels, attackers can also bypass JavaScript verification and modify requests to perform XSS attacks, for example:
After learning about the principles and dangers of XSS attacks, it is not difficult to prevent them. The following provides a simple function for PHP to prevent XSS attacks:
<? PHP/*** @ blog http://www.codetc.com * @ param $ string * @ param $ low security level low */function clean_xss (& $ string, $ low = False) {if (! Is_array ($ string) {$ string = trim ($ string); $ string = strip_tags ($ string); $ string = htmlspecialchars ($ string); if ($ low) {return True;} $ string = str_replace (array ('"',"\\","'","/",".. ",".. /",". /"," // "),'', $ string); $ no = '/% 0 [0-8bcef]/'; $ string = preg_replace ($ no ,'', $ string); $ no = '/% 1 [0-9a-f]/'; $ string = preg_replace ($ no, '', $ string ); $ no = '/[\ x00-\ x08 \ x0B \ x0C \ x0E -\ X1F \ x7F] +/s'; $ string = preg_replace ($ no, '', $ string); return True ;}$ keys = array_keys ($ string ); foreach ($ keys as $ key) {clean_xss ($ string [$ key]) ;}// just a test $ str = 'codetc. com <meta http-equiv = "refresh" content = "0;"> '; clean_xss ($ str); // If you comment out this, you will know that xss attacks are amazing echo $ str;?>