Home Backend Development PHP Tutorial Method analysis of Yii2's XSS attack prevention strategy

Method analysis of Yii2's XSS attack prevention strategy

Jun 19, 2018 pm 01:44 PM
xss yii2 Attack prevention

This article mainly introduces the XSS attack prevention strategy of Yii2. It analyzes the principle of XSS attack and the corresponding prevention strategy of Yii2 in more detail. Friends in need can refer to it.

This article describes the example of Yii2 XSS attack prevention strategies. Share it with everyone for your reference, the details are as follows:

XSS vulnerability repair

Principle: Do not believe the data entered by the customer
Note: The attack code is not necessarily in < ;script>

① Mark important cookies as http only, so that the document.cookie statement in Javascript cannot obtain the cookie.
② Only allow users to enter us expected data. For example: In the age textbox, users are only allowed to enter numbers. Characters other than numbers are filtered out.
③ Html Encode processing of data
④ Filter or remove special Html tags, such as: script, iframe, < for <, > for >, " for
⑤ Filter JavaScript events Tag of. For example "onclick=", "onfocus" etc.

XSS prevention in Yii

<?php echo CHtml::encode($user->name) ?>
Copy after login

Source code of this method:

/**
* Encodes special characters into HTML entities.
* The [[\yii\base\Application::charset|application charset]] will be used for encoding.
* @param string $content the content to be encoded
* @param boolean $doubleEncode whether to encode HTML entities in `$content`. If false,
* HTML entities in `$content` will not be further encoded.
* @return string the encoded content
* @see decode()
* @see http://www.php.net/manual/en/function.htmlspecialchars.php
*/
public static function encode($content, $doubleEncode = true)
{
  return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app->charset, $doubleEncode);
}
Copy after login

htmlspecialchars & htmlentities & urlencode The difference between the three:

http://php.net/manual/zh/function.htmlspecialchars.php
http:// php.net/manual/zh/function.htmlentities.php
http://cn2.php.net/manual/zh/function.urlencode.php

Available flags constants
Constant Name Description
ENT_COMPAT Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES Will convert both double and single quotes.
ENT_NOQUOTES Will leave both double and single quotes unconverted.
ENT_IGNORE Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications.
ENT_SUBSTITUTE Replace invalid code unit sequences with a Unicode Replacement Character U FFFD (UTF-8) or FFFD; (otherwise) instead of returning an empty string.
ENT_DISALLOWED Replace invalid code points for the given document type with a Unicode Replacement Character U FFFD (UTF-8) or FFFD; (otherwise) instead of leaving them as is. This may be useful, for instance , to ensure the well-formedness of XML documents with embedded external content.
ENT_HTML401 Handle code as HTML 4.01.
ENT_XML1 Handle code as XML 1.
ENT_XHTML Handle code as XHTML.
ENT_HTML5 Handle code as HTML 5.

htmlspecialchars

Convert special characters to HTML entities

string htmlspecialchars ( 
      string $string 
      [, int $flags = ENT_COMPAT | ENT_HTML401 
      [, string $encoding = ini_get("default_charset") 
      [, bool $double_encode = true ]
    ]
  ] 
)
Copy after login

The translations performed are:

& (ampersand) becomes &
" (double quote) becomes " when ENT_NOQUOTES is not set.
' (single quote) becomes ' (or ') only when ENT_QUOTES is set .
< (less than) becomes <
> (greater than) becomes >

<?php
$new = htmlspecialchars("<a href=&#39;test&#39;>Test</a>", ENT_QUOTES);
echo $new; // <a href=&#39;test&#39;>Test</a>
?>
Copy after login

htmlentities

Convert all applicable characters to HTML entities

string htmlentities ( 
      string $string 
      [, int $flags = ENT_COMPAT | ENT_HTML401 
      [, string $encoding = ini_get("default_charset") 
      [, bool $double_encode = true ]
    ]
  ] 
)
Copy after login

##

<?php
$str = "A &#39;quote&#39; is <b>bold</b>";
// Outputs: A &#39;quote&#39; is <b>bold</b>
echo htmlentities($str);
// Outputs: A &#39;quote&#39; is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);
?>
Copy after login

urlencode

URL encoding is to comply with the URL specification. Because in the standard URL specification, Chinese and many characters are not allowed to appear in the URL.

For example, search for "test Chinese characters" in Baidu. The URL will become

http://www.baidu.com/s?wd=���պ���&rsv_bp=0&rsv_spt=3&inputT=7477

The so-called URL encoding is: put all non-letters Numeric characters will be replaced with a percent sign (%) followed by two hexadecimal digits, and spaces will be encoded as plus signs ( )

All non-alphanumeric characters in this string except -_. Will be replaced with a percent sign (%) followed by two hexadecimal digits, and spaces are encoded as plus signs ( ). This encoding is the same as the encoding of WWW form POST data, and the same encoding as the application/x-www-form-urlencoded media type. For historical reasons, this encoding differs from the RFC1738 encoding (see rawurlencode()) in encoding spaces as plus signs ( ).

<?php
echo &#39;<a href="mycgi?foo=&#39;, urlencode($userinput), &#39;">&#39;;
?>
Copy after login

<?php
$query_string = &#39;foo=&#39; . urlencode($foo) . &#39;&bar=&#39; . urlencode($bar);
echo &#39;<a href="mycgi?&#39; . htmlentities($query_string) . &#39;">&#39;;
?>
Copy after login

The above is the entire content of this article, I hope it will help everyone learn Helpful, please pay attention to the PHP Chinese website for more related content!

Related recommendations:

How to implement Yii cache cleanup

How to deal with routing links being forwarded in Yii2.0 Basic code righteous

The above is the detailed content of Method analysis of Yii2's XSS attack prevention strategy. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

Cross-site scripting (XSS) and cross-site request forgery (CSRF) protection in Laravel Cross-site scripting (XSS) and cross-site request forgery (CSRF) protection in Laravel Aug 13, 2023 pm 04:43 PM

Cross-site scripting (XSS) and cross-site request forgery (CSRF) protection in Laravel With the development of the Internet, network security issues have become more and more serious. Among them, Cross-SiteScripting (XSS) and Cross-SiteRequestForgery (CSRF) are one of the most common attack methods. Laravel, as a popular PHP development framework, provides users with a variety of security mechanisms

How to remove jquery in yii2 How to remove jquery in yii2 Feb 17, 2023 am 09:55 AM

How to remove jquery from yii2: 1. Edit the AppAsset.php file and comment out the "yii\web\YiiAsset" value in the variable $depends; 2. Edit the main.php file and add the configuration "'yii" under the field "components" \web\JqueryAsset' => ['js' => [],'sourcePath' => null,]," to remove the jquery script.

How to use Nginx to protect against port scanning attacks How to use Nginx to protect against port scanning attacks Jun 10, 2023 pm 12:18 PM

In the current Internet environment, security has always been one of the most concerning issues for network administrators and website developers. Among them, port scanning attacks are a common security vulnerability. Attackers scan open ports on a website to identify potential vulnerabilities. In order to avoid security threats caused by port scanning attacks, more and more enterprises and websites choose to use Nginx as their web server. This article will introduce how to use Nginx to prevent port scanning attacks. 1. What is a port scanning attack? Port scanning refers to an attacker using TCP or U

How to defend against XSS and remote code execution attacks in PHP How to defend against XSS and remote code execution attacks in PHP Jun 30, 2023 am 08:04 AM

How to use PHP to defend against cross-site scripting (XSS) and remote code execution attacks Introduction: In today's Internet world, security has become a vital issue. XSS (cross-site scripting) and remote code execution attacks are two of the most common security vulnerabilities. This article will explore how to use the PHP language to defend against these two attacks and provide several methods and techniques to protect your website from these attacks. 1. Understand XSS attacks XSS attacks refer to attackers obtaining users’ personal information by injecting malicious scripts on websites.

PHP security protection and attack prevention in mini program development PHP security protection and attack prevention in mini program development Jul 07, 2023 am 08:55 AM

PHP security protection and attack prevention in mini program development With the rapid development of the mobile Internet, mini programs have become an important part of people's lives. As a powerful and flexible back-end development language, PHP is also widely used in the development of small programs. However, security issues have always been an aspect that needs attention in program development. This article will focus on PHP security protection and attack prevention in small program development, and provide some code examples. XSS (Cross-site Scripting Attack) Prevention XSS attack refers to hackers injecting malicious scripts into web pages

Analysis of secure XSS filtering technology in PHP Analysis of secure XSS filtering technology in PHP Jun 29, 2023 am 09:49 AM

PHP is a programming language widely used in website development, but when using PHP to develop websites, security issues often cause people to worry. One of them is Cross-SiteScripting (XSS), which is a common network security vulnerability. To solve this problem, PHP provides some secure XSS filtering technologies. This article will introduce the principles and usage of secure XSS filtering technology in PHP. First, we need to understand what an XSS attack is. XSS attack

A few selected CTF exercises will help you learn the yii2 framework! A few selected CTF exercises will help you learn the yii2 framework! Feb 23, 2022 am 10:33 AM

This article will introduce you to the yii2 framework, share a few CTF exercises, and use them to learn the yii2 framework. I hope it will be helpful to everyone.

Security Best Practices for PHP and Vue.js Development: Preventing XSS Attacks Security Best Practices for PHP and Vue.js Development: Preventing XSS Attacks Jul 06, 2023 pm 01:37 PM

Best Practices for PHP and Vue.js Development Security: Preventing XSS Attacks With the rapid development of the Internet, network security issues are becoming more and more important. Among them, XSS (cross-site scripting attack) is a very common type of network attack that aims to exploit the security vulnerabilities of the website to inject malicious code into users or tamper with web page content. In PHP and Vue.js development, it is very important to adopt some security best practices to prevent XSS attacks. This article will introduce some commonly used methods to prevent XSS attacks and provide corresponding codes.

See all articles