Home Backend Development PHP Tutorial Talk about how to prevent XSS cross-site scripting attacks in PHP

Talk about how to prevent XSS cross-site scripting attacks in PHP

Jul 17, 2020 pm 03:41 PM
xss attack

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(&#39;/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/&#39;,&#39;/script/&#39;,&#39;/javascript/&#39;,&#39;/vbscript/&#39;,&#39;/expression/&#39;,&#39;/applet/&#39;
   ,&#39;/meta/&#39;,&#39;/xml/&#39;,&#39;/blink/&#39;,&#39;/link/&#39;,&#39;/style/&#39;,&#39;/embed/&#39;,&#39;/object/&#39;,&#39;/frame/&#39;,&#39;/layer/&#39;,&#39;/title/&#39;,&#39;/bgsound/&#39;
   ,&#39;/base/&#39;,&#39;/onload/&#39;,&#39;/onunload/&#39;,&#39;/onchange/&#39;,&#39;/onsubmit/&#39;,&#39;/onreset/&#39;,&#39;/onselect/&#39;,&#39;/onblur/&#39;,&#39;/onfocus/&#39;,
   &#39;/onabort/&#39;,&#39;/onkeydown/&#39;,&#39;/onkeypress/&#39;,&#39;/onkeyup/&#39;,&#39;/onclick/&#39;,&#39;/ondblclick/&#39;,&#39;/onmousedown/&#39;,&#39;/onmousemove/&#39;
   ,&#39;/onmouseout/&#39;,&#39;/onmouseover/&#39;,&#39;/onmouseup/&#39;,&#39;/onunload/&#39;);
     
   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); //给单引号(&#39;)、双引号(")、反斜线(\)与 NUL(NULL 字符)
             #加上反斜线转义
          }
          $value       = preg_replace($ra,&#39;&#39;,$value);     //删除非打印字符,粗暴式过滤xss可疑字符串
          $arr[$key]     = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体
        }
        else
        {
          SafeFilter($arr[$key]);
        }
     }
   }
}
?>
$str = &#39;www.90boke.com<meta http-equiv="refresh" content="0;">&#39;;
SafeFilter ($str); //如果你把这个注释掉,提交之后就会无休止刷新
echo $str;
Copy after login
//------------------------------php防注入和XSS攻击通用过滤-----Start--------------------------------------------//
function string_remove_xss($html) {
    preg_match_all("/\<([^\<]+)\>/is", $html, $ms);
 
    $searchs[] = &#39;<&#39;;
    $replaces[] = &#39;<&#39;;
    $searchs[] = &#39;>&#39;;
    $replaces[] = &#39;>&#39;;
 
    if ($ms[1]) {
        $allowtags = &#39;img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote&#39;;
        $ms[1] = array_unique($ms[1]);
        foreach ($ms[1] as $value) {
            $searchs[] = "<".$value.">";
 
            $value = str_replace(&#39;&&#39;, &#39;_uch_tmp_str_&#39;, $value);
            $value = string_htmlspecialchars($value);
            $value = str_replace(&#39;_uch_tmp_str_&#39;, &#39;&&#39;, $value);
 
            $value = str_replace(array(&#39;\\&#39;, &#39;/*&#39;), array(&#39;.&#39;, &#39;/.&#39;), $value);
            $skipkeys = array(&#39;onabort&#39;,&#39;onactivate&#39;,&#39;onafterprint&#39;,&#39;onafterupdate&#39;,&#39;onbeforeactivate&#39;,&#39;onbeforecopy&#39;,&#39;onbeforecut&#39;,&#39;onbeforedeactivate&#39;,
                    &#39;onbeforeeditfocus&#39;,&#39;onbeforepaste&#39;,&#39;onbeforeprint&#39;,&#39;onbeforeunload&#39;,&#39;onbeforeupdate&#39;,&#39;onblur&#39;,&#39;onbounce&#39;,&#39;oncellchange&#39;,&#39;onchange&#39;,
                    &#39;onclick&#39;,&#39;oncontextmenu&#39;,&#39;oncontrolselect&#39;,&#39;oncopy&#39;,&#39;oncut&#39;,&#39;ondataavailable&#39;,&#39;ondatasetchanged&#39;,&#39;ondatasetcomplete&#39;,&#39;ondblclick&#39;,
                    &#39;ondeactivate&#39;,&#39;ondrag&#39;,&#39;ondragend&#39;,&#39;ondragenter&#39;,&#39;ondragleave&#39;,&#39;ondragover&#39;,&#39;ondragstart&#39;,&#39;ondrop&#39;,&#39;onerror&#39;,&#39;onerrorupdate&#39;,
                    &#39;onfilterchange&#39;,&#39;onfinish&#39;,&#39;onfocus&#39;,&#39;onfocusin&#39;,&#39;onfocusout&#39;,&#39;onhelp&#39;,&#39;onkeydown&#39;,&#39;onkeypress&#39;,&#39;onkeyup&#39;,&#39;onlayoutcomplete&#39;,
                    &#39;onload&#39;,&#39;onlosecapture&#39;,&#39;onmousedown&#39;,&#39;onmouseenter&#39;,&#39;onmouseleave&#39;,&#39;onmousemove&#39;,&#39;onmouseout&#39;,&#39;onmouseover&#39;,&#39;onmouseup&#39;,&#39;onmousewheel&#39;,
                    &#39;onmove&#39;,&#39;onmoveend&#39;,&#39;onmovestart&#39;,&#39;onpaste&#39;,&#39;onpropertychange&#39;,&#39;onreadystatechange&#39;,&#39;onreset&#39;,&#39;onresize&#39;,&#39;onresizeend&#39;,&#39;onresizestart&#39;,
                    &#39;onrowenter&#39;,&#39;onrowexit&#39;,&#39;onrowsdelete&#39;,&#39;onrowsinserted&#39;,&#39;onscroll&#39;,&#39;onselect&#39;,&#39;onselectionchange&#39;,&#39;onselectstart&#39;,&#39;onstart&#39;,&#39;onstop&#39;,
                    &#39;onsubmit&#39;,&#39;onunload&#39;,&#39;javascript&#39;,&#39;script&#39;,&#39;eval&#39;,&#39;behaviour&#39;,&#39;expression&#39;,&#39;style&#39;,&#39;class&#39;);
            $skipstr = implode(&#39;|&#39;, $skipkeys);
            $value = preg_replace(array("/($skipstr)/i"), &#39;.&#39;, $value);
            if (!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) {
                $value = &#39;&#39;;
            }
            $replaces[] = empty($value) ? &#39;&#39; : "<" . str_replace(&#39;"&#39;, &#39;"&#39;, $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(&#39;&&#39;, &#39;"&#39;, &#39;<&#39;, &#39;>&#39;), array(&#39;&&#39;, &#39;"&#39;, &#39;<&#39;, &#39;>&#39;), $string);
            if (strpos($string, &#39;&#&#39;) !== false) {
                $string = preg_replace(&#39;/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/&#39;, &#39;&\\1&#39;, $string);
            }
        } else {
            if (PHP_VERSION < &#39;5.4.0&#39;) {
                $string = htmlspecialchars($string, $flags);
            } else {
                if (!defined(&#39;CHARSET&#39;) || (strtolower(CHARSET) == &#39;utf-8&#39;)) {
                    $charset = &#39;UTF-8&#39;;
                } else {
                    $charset = &#39;ISO-8859-1&#39;;
                }
                $string = htmlspecialchars($string, $flags, $charset);
            }
        }
    }
 
    return $string;
}

//------------------php防注入和XSS攻击通用过滤-----End--------------------------------------------//
Copy after login

PHP中的设置

PHP5.2以上版本已支持HttpOnly参数的设置,同样也支持全局的HttpOnly的设置,在php.ini中

----------------------------------------------------- 
 session.cookie_httponly = 
-----------------------------------------------------
Copy after login

设置其值为1或者TRUE,来开启全局的Cookie的HttpOnly属性,当然也支持在代码中来开启:

<?php ini_set("session.cookie_httponly", 1);   
// or session_set_cookie_params(0, NULL, NULL, NULL, TRUE);   
?>
Copy after login

Cookie操作函数setcookie函数和setrawcookie函数也专门添加了第7个参数来做为HttpOnly的选项,开启方法为:

<?php  
setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE);   
setrawcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE);  
?>
Copy after login

相关推荐: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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to protect against cross-site scripting (XSS) attacks using PHP How to protect against cross-site scripting (XSS) attacks using PHP Jun 29, 2023 am 10:46 AM

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.

How do XSS vulnerabilities work? How do XSS vulnerabilities work? Feb 19, 2024 pm 07:31 PM

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 PHP data filtering: preventing XSS and CSRF attacks Jul 29, 2023 pm 03:33 PM

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

Cross-site scripting (XSS) attack prevention in Go: best practices and tips Cross-site scripting (XSS) attack prevention in Go: best practices and tips Jun 17, 2023 pm 12:46 PM

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

Common network security issues and solutions in Java development Common network security issues and solutions in Java development Oct 09, 2023 pm 06:36 PM

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

How to avoid SQL injection and XSS attacks in PHP language development? How to avoid SQL injection and XSS attacks in PHP language development? Jun 09, 2023 pm 06:27 PM

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

Things to note when developing ThinkPHP: Preventing XSS attacks Things to note when developing ThinkPHP: Preventing XSS attacks Nov 22, 2023 pm 08:13 PM

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

Learn security precautions: Use PHP to avoid XSS attacks Learn security precautions: Use PHP to avoid XSS attacks Jun 22, 2023 am 08:48 AM

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

See all articles