


Talk about how to prevent XSS cross-site scripting attacks in PHP
PHP防止XSS跨站脚本攻击的方法:是针对非法的HTML代码包括单双引号等,使用htmlspecialchars()函数 。
在使用htmlspecialchars()函数的时候注意第二个参数, 直接用htmlspecialchars($string) 的话,第二个参数默认是ENT_COMPAT,函数默认只是转化双引号(“), 不对单引号(‘)做转义.
所以,htmlspecialchars函数更多的时候要加上第二个参数, 应该这样用: htmlspecialchars($string,ENT_QUOTES).当然,如果需要不转化任何引号,用htmlspecialchars($string,ENT_NOQUOTES).
另外, 尽量少用htmlentities, 在全部英文的时候htmlentities和htmlspecialchars没有区别,都可以达到目的.但是,中文情况下, htmlentities却会转化所有的html代码,连同里面的它无法识别的中文字符也给转化了。
htmlentities和htmlspecialchars这两个函数对 '之类的字符串支持不好,都不能转化, 所以用htmlentities和htmlspecialchars转化的字符串只能防止XSS攻击,不能防止SQL注入攻击.
所有有打印的语句如echo,print等 在打印前都要使用htmlentities() 进行过滤,这样可以防止Xss,注意中文要写出htmlentities($name,ENT_NOQUOTES,GB2312) 。
(1).网页不停地刷新 ''
(2).嵌入其它网站的链接 除了通过正常途径输入XSS攻击字符外,还可以绕过JavaScript校验,通过修改请求达到XSS攻击的目的.
<?php //php防注入和XSS攻击通用过滤 $_GET && SafeFilter($_GET); $_POST && SafeFilter($_POST); $_COOKIE && SafeFilter($_COOKIE); function SafeFilter (&$arr) { $ra=Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','/script/','/javascript/','/vbscript/','/expression/','/applet/' ,'/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/title/','/bgsound/' ,'/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/', '/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/' ,'/onmouseout/','/onmouseover/','/onmouseup/','/onunload/'); if (is_array($arr)) { foreach ($arr as $key => $value) { if (!is_array($value)) { if (!get_magic_quotes_gpc()) //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。 { $value = addslashes($value); //给单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符) #加上反斜线转义 } $value = preg_replace($ra,'',$value); //删除非打印字符,粗暴式过滤xss可疑字符串 $arr[$key] = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体 } else { SafeFilter($arr[$key]); } } } } ?> $str = 'www.90boke.com<meta http-equiv="refresh" content="0;">'; SafeFilter ($str); //如果你把这个注释掉,提交之后就会无休止刷新 echo $str;
//------------------------------php防注入和XSS攻击通用过滤-----Start--------------------------------------------// function string_remove_xss($html) { preg_match_all("/\<([^\<]+)\>/is", $html, $ms); $searchs[] = '<'; $replaces[] = '<'; $searchs[] = '>'; $replaces[] = '>'; if ($ms[1]) { $allowtags = 'img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote'; $ms[1] = array_unique($ms[1]); foreach ($ms[1] as $value) { $searchs[] = "<".$value.">"; $value = str_replace('&', '_uch_tmp_str_', $value); $value = string_htmlspecialchars($value); $value = str_replace('_uch_tmp_str_', '&', $value); $value = str_replace(array('\\', '/*'), array('.', '/.'), $value); $skipkeys = array('onabort','onactivate','onafterprint','onafterupdate','onbeforeactivate','onbeforecopy','onbeforecut','onbeforedeactivate', 'onbeforeeditfocus','onbeforepaste','onbeforeprint','onbeforeunload','onbeforeupdate','onblur','onbounce','oncellchange','onchange', 'onclick','oncontextmenu','oncontrolselect','oncopy','oncut','ondataavailable','ondatasetchanged','ondatasetcomplete','ondblclick', 'ondeactivate','ondrag','ondragend','ondragenter','ondragleave','ondragover','ondragstart','ondrop','onerror','onerrorupdate', 'onfilterchange','onfinish','onfocus','onfocusin','onfocusout','onhelp','onkeydown','onkeypress','onkeyup','onlayoutcomplete', 'onload','onlosecapture','onmousedown','onmouseenter','onmouseleave','onmousemove','onmouseout','onmouseover','onmouseup','onmousewheel', 'onmove','onmoveend','onmovestart','onpaste','onpropertychange','onreadystatechange','onreset','onresize','onresizeend','onresizestart', 'onrowenter','onrowexit','onrowsdelete','onrowsinserted','onscroll','onselect','onselectionchange','onselectstart','onstart','onstop', 'onsubmit','onunload','javascript','script','eval','behaviour','expression','style','class'); $skipstr = implode('|', $skipkeys); $value = preg_replace(array("/($skipstr)/i"), '.', $value); if (!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) { $value = ''; } $replaces[] = empty($value) ? '' : "<" . str_replace('"', '"', $value) . ">"; } } $html = str_replace($searchs, $replaces, $html); return $html; } //php防注入和XSS攻击通用过滤 function string_htmlspecialchars($string, $flags = null) { if (is_array($string)) { foreach ($string as $key => $val) { $string[$key] = string_htmlspecialchars($val, $flags); } } else { if ($flags === null) { $string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string); if (strpos($string, '&#') !== false) { $string = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string); } } else { if (PHP_VERSION < '5.4.0') { $string = htmlspecialchars($string, $flags); } else { if (!defined('CHARSET') || (strtolower(CHARSET) == 'utf-8')) { $charset = 'UTF-8'; } else { $charset = 'ISO-8859-1'; } $string = htmlspecialchars($string, $flags, $charset); } } } return $string; } //------------------php防注入和XSS攻击通用过滤-----End--------------------------------------------//
PHP中的设置
PHP5.2以上版本已支持HttpOnly参数的设置,同样也支持全局的HttpOnly的设置,在php.ini中
----------------------------------------------------- session.cookie_httponly = -----------------------------------------------------
设置其值为1或者TRUE,来开启全局的Cookie的HttpOnly属性,当然也支持在代码中来开启:
<?php ini_set("session.cookie_httponly", 1); // or session_set_cookie_params(0, NULL, NULL, NULL, TRUE); ?>
Cookie操作函数setcookie函数和setrawcookie函数也专门添加了第7个参数来做为HttpOnly的选项,开启方法为:
<?php setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE); setrawcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE); ?>
相关推荐:PHP教程
The above is the detailed content of Talk about how to prevent XSS cross-site scripting attacks in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to Use PHP to Defend Cross-Site Scripting (XSS) Attacks With the rapid development of the Internet, Cross-SiteScripting (XSS) attacks are one of the most common network security threats. XSS attacks mainly achieve the purpose of obtaining user sensitive information and stealing user accounts by injecting malicious scripts into web pages. To protect the security of user data, developers should take appropriate measures to defend against XSS attacks. This article will introduce some commonly used PHP technologies to defend against XSS attacks.

What is the principle of XSS attack? Specific code examples are needed. With the popularity and development of the Internet, the security of Web applications has gradually become the focus of attention. Among them, Cross-SiteScripting (XSS for short) is a common security vulnerability that web developers must pay attention to. XSS attacks are performed by injecting malicious script code into a Web page and executing it in the user's browser. This allows the attacker to control the user's browser and obtain the user's sensitive information.

PHP Data Filtering: Preventing XSS and CSRF Attacks With the development of the Internet, network security has become one of the focuses of people's attention. In website development, it is very important to filter and verify user-submitted data, especially to prevent XSS (cross-site scripting attacks) and CSRF (cross-site request forgery attacks) attacks. This article will introduce how to use PHP to prevent these two common security vulnerabilities and provide some sample code for reference. Preventing XSS attacks XSS attacks refer to malicious attackers injecting malicious scripts or codes to tamper with

With the rapid development of the Internet, website security issues have become a major problem in the online world. Cross-site scripting (XSS) attack is a common security vulnerability that exploits website weaknesses to inject malicious scripts into web pages to steal and tamper with user information. As an efficient and safe programming language, Go language provides us with powerful tools and techniques to prevent XSS attacks. This article will introduce some best practices and techniques to help Go language developers effectively prevent and resolve XSS attacks. for all inputs

Summary of common network security issues and solutions in Java development: With the popularization of the Internet, network security issues have become increasingly prominent. During Java development, we need to consider how to protect the security of network communications. This article will introduce some common network security problems and provide corresponding solutions and code examples. 1. Cross-site scripting attack (XSS) XSS attack refers to an attack method that obtains user sensitive information by injecting malicious scripts into web pages. To prevent XSS attacks, we can use regular input checking

As the Internet becomes more and more widely used, security issues become more and more noticeable. In PHP development, SQL injection and XSS attacks are the two most common security issues. This article explains how to avoid both attacks. 1. What is SQL injection? SQL injection refers to an attacker exploiting web application vulnerabilities to cause the database server to run in a manner beyond the original design intention by entering SQL instructions. Attackers can use these vulnerabilities to perform malicious operations, such as reading and writing data, obtaining administrator privileges, etc. 2. How to avoid

ThinkPHP is a popular PHP development framework that provides powerful features and easy-to-use tools, allowing developers to quickly build efficient web applications. However, during the development process, we need to pay attention to the common network security threat of XSS (cross-site scripting attack). XSS attack is a technique that injects malicious scripts to steal user information or spread malware. This article will discuss some precautions that need to be taken into consideration to prevent XSS attacks during the development of ThinkPHP. First, we need

In the Internet era, with the continuous popularity and development of Web applications, injection and cross-site scripting attacks (XSS) have become a focus of security prevention work. Among them, XSS attacks are carried out by attackers by inserting malicious scripts into Web pages. PHP, as a server-side scripting language, is widely used in Web development. How to use PHP to avoid XSS attacks has become a must for developers. Right question. First, understanding how XSS attacks are implemented is crucial to preventing XSS attacks. XSS
