


PHP filtering and processing of special characters in form submission_PHP tutorial
前天天缘把博客文章做过一次内容批量修改,由于在源程序存在BUG,导致很多路径或代码中的反斜杠被无辜去除,昨天通过bankw3000网友的留言才发现这个问题,已做了部分修正不排除还有些路径存在问题,如果大家发现博客上存在路径丢失反斜杠\的问题,欢迎留言反馈,天缘会再做修正。天缘本文特别把PHP关于表单提交特殊字符的处理方法做个汇总,主要涉及htmlspecialchars/addslashes/stripslashes/strip_tags/mysql_real_escape_string等几个函数联合使用,与大家共同交流。
一、几个与特殊字符处理有关的PHP函数
函数名 |
释义 |
介绍 |
htmlspecialchars |
将与、单双引号、大于和小于号化成HTML格式 |
&转成& |
htmlentities() |
所有字符都转成HTML格式 |
除上面htmlspecialchars字符外,还包括双字节字符显示成编码等。 |
|
|
|
addslashes |
单双引号、反斜线及NULL加上反斜线转义 |
被改的字符包括单引号(')、双引号(")、反斜线backslash (\) 以及空字符NULL。 |
stripslashes |
去掉反斜线字符 |
去掉字符串中的反斜线字符。若是连续二个反斜线,则去掉一个,留下一个。若只有一个反斜线,就直接去掉。 |
|
|
|
quotemeta |
加入引用符号 |
将字符串中含有. \\ + * ? [ ^ ] ( $ ) 等字符的前面加入反斜线"\" 符号。 |
nl2br() |
将换行字符转成 |
|
strip_tags |
去掉HTML及PHP标记 |
去掉字符串中任何HTML标记和PHP标记,包括标记封堵之间的内容。注意如果字符串HTML及PHP标签存在错误,也会返回错误。 |
mysql_real_escape_string |
转义SQL字符串中的特殊字符 |
转义\x00 \n \r 空格 \ ' " \x1a,针对多字节字符处理很有效。mysql_real_escape_string会判断字符集,mysql_escape_string则不用考虑。 |
其它字符串处理函数,请参考:PHP常用字符串正则替换及 剖分函数比较。
下面针对常用表单特殊字符处理进行总结:
测试字符串:
1 $dbstr='D:\test
2 http://www.metsky.com,天缘博客
3 \'!=\'1\' OR \'1\'
4
5
6
7
8 PHP OUTPUT"; ?>';
Test code:
01 header("Content-Type: text/html; charset=UTF-8");
02 echo "------------------------------------------------ -------
rn";
03 echo $dbstr."
rn--------------------------------------------- ------------------
rn";
04 $str=fnAddSlashes($_POST['dd']);
05 echo $str."
rn---------------------------------------- ------------------
rn";
06
07 $str = preg_replace("/s(?=s)/","\1",$str);//Retain only one
for multiple consecutive spaces
08 $str = str_replace("r","
",$str);
09 $str = str_replace("n","
",$str);
10 $str = preg_replace("/((
)+)/i", "
", $str);//Multiple consecutive
tags only Keep one
11
12 $str=stripslashes($str);
13 echo strip_tags($str)."
rn---------------------------------- --------------------
rn";
14 echo htmlspecialchars($str)."
rn---------------------------------- --------------------
rn";
15 echo htmlentities($str)."
rn---------------------------------- --------------------
rn";
16 echo mysql_escape_string($str)."
rn---------------------------------- --------------------
rn";
The string contains: backslash paths, single and double quotes, HTML tags, links, unblocked HTML tags, database syntax tolerance, JS execution judgment, PHP execution judgment, multiple consecutive carriage returns, line feeds and spaces. Some of these concepts are inclusive, the same below.
The source code output is as follows (JS script will be executed):
2. Form submission data processing
1. Forced to add backslash
Since some hosts enable the magic quote get_magic_quotes_gpc by default, and some may turn it off, it is best to force the addition of backslashes in the program so that they can be processed uniformly. The characters involve single quotes, double quotes and backslashes.
1 function fnAddSlashes($data)
2 {
3 If(!get_magic_quotes_gpc()) //Only add escaping to the data coming from POST/GET/cookie
4 return is_array($data)?array_map('addslashes',$data):addslashes($data);
5 else
6 return $data;
7}
Use the function fnAddSlashes($data); the result is as shown below (the JS script will not be executed, but the HTML, JS and PHP tags still need to be fault-tolerant):
The result after using stripslashes, newline replacement, and space replacement is as follows:
2. Processing of special characters
The following are several commonly used string processing, which can be chosen depending on the specific situation. Since the submitted form data has been escaped above, if you need to replace or filter the content, you need to consider the impact of addslashes on relevant characters, and you need to consider the addition of backslashes when replacing or searching. Other character substitutions have no effect, such as rn substitution.
A. Only keep one
for multiple consecutive spaces.
$data = preg_replace("/s(?=s)/","\1",$data );//Retain only one of multiple consecutive spaces
B. Replace carriage return and line feed with
$data = str_replace("r","
",$data );
$data = str_replace("n","
",$data );
//The default
in html is not blocked, and
is blocked in xhtml. It is recommended to use
. More differences: http://stackoverflow.com/questions/1946426/ html-5-is-it-br-br-or-br
C. Multiple consecutive
only keep one
$data = preg_replace("/((
)+)/i", "
", $data );//Multiple consecutive
tags are only retained a
D. Filter all HTML tags
This method filters out all potentially dangerous tags, including HTML, links, unblocked HTML tags, JS, and PHP.
Use the function strip_tags($data)
After using this function, all HTML tags (including links), PHP tags, JS codes, etc. will be filtered. The link will retain the original text of the link and only remove the tag and href part of the content. The PHP tag and JS tag will be removed as a whole. Including the content in the middle, as shown below:
E. Don’t filter tags, just HTML them
This method is to process all the original submitted content as ordinary text.
Use the function htmlspecialchars($data). After the function is executed, all submitted data will be displayed as ordinary text, as shown below:
The execution result of using the htmlentities function (garbled characters are displayed in Chinese):
3. Write to the database
After using addslashes($data), advanced trusted users can directly write to the database, but addslashes cannot intercept single quotes replaced by 0xbf27, so it is best to use mysql_real_escape_string or mysql_escape_string to escape, but it needs to be removed before escaping. Backslash (assuming addslashes is enabled by default).
01 function fnEscapeStr($data)
02
03 {
04
05 if (get_magic_quotes_gpc())
06 {
07 $data= stripslashes($value);
08}
09 $data="'". mysql_escape_string($value) ."'";
10 return $data;
11}
12
13 $data=fnEscapeStr($data);
After execution, the following picture appears:
4. Instant display after submission
1. If addslashes are used above, the backslash must be removed before echoing the data
Use the function stripslashes($data)
Note that this function is only for data processed by addslashes($data). Use it with caution, otherwise it will cause backslashes to be lost (such as content folder path dividing lines, drive paths, etc.). An error occurred in Tianyuan a few days ago. It is because this function was used when reading the database (the code is old and I forgot to modify it) that when writing to the database again, many backslashes in the paths were lost, otherwise there would be no article.
2. Use the function htmlspecialchars($data). After this function is executed, all submitted data will be displayed as text. Unless special processing is allowed for links, etc., htmlspecialchars can be used for output, especially for unblocked HTML tags. If Without filtering or tag conversion, the output may cause layout confusion.
The use of htmlentities is not recommended. On the one hand, it will cause great reading difficulties for the output source code. On the other hand, using the htmlentities function will cause double-byte characters such as Chinese to display a bunch of garbled characters. Other characters are displayed normally.
The second output method, depending on the situation, can be output directly if it is confirmed that there are no illegal tags or potential execution risks.

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

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

SublimeText3 Linux new version
SublimeText3 Linux latest version
