Home > Article > Backend Development > The difference between the usage of stripslashes and addslashes in php_PHP tutorial
In PHP we often use stripslashes and addslashes. Let me introduce in detail how to use stripslashes and addslashes and the differences between them.
addslashes
The addslashes() function adds a backslash before the specified predefined characters.
These predefined characters are:
•Single quote (')
•Double quotes (")
•Backslash ()
•NULL
In this example, we want to add a backslash to a predefined character in a string:
Note: By default, the PHP instruction magic_quotes_gpc is on, automatically running addslashes() for all GET, POST and COOKIE data. Do not use addslashes() on strings that have been escaped by magic_quotes_gpc, as this will result in double escaping. When encountering this situation, you can use the function get_magic_quotes_gpc() to detect it.
The code is as follows
|
Copy code
|
||||
/** * Determine whether to use addslashes() to process * * @param String $str* */function str_addslashes($str, $db_type='mysql') { if(get_magic_quotes_gpc()){ switch($db_type){ case "access":$str = stripslashes($str); $str = str_replace("'","''",$str);
} }else { switch($db_type){ case "mysql":$str = addslashes($str); break;case "access": $str = str_replace("'","''",$str);break; } |
}
Code
The code is as followsCopy code
|
//Submit data, or prepare variables:
$Content=addslashes("This is data, whether there are single quotes or variables");
//Insert data into the database, code omitted
//Start displaying data
$Content="Data read from database";
if(get_magic_quotes_gpc()){
$Content=stripslashes($Content);
}
echo $Content;
Summary of differences
When magic_quotes_gpc = On, the data processed using addslashes() will be saved in the database in the form of '. If you output it directly at this time, you will find that there are more contents than you expected, so stripslashes() appears, it can be removed (different from str_replace("", "",$Str)).
When magic_quotes_gpc = Off, the data processed using addslashes() will be saved in the database in the form of '. There is no problem mentioned above. addslashes() plays the role of inserting data without errors. If at this time If output directly, the data is normal. No need to use stripslashes() anymore.
addslashes() and stripslashes() are exactly the opposite. Direct memory: addslashes() adds one, stripslashes() removes one
http://www.bkjia.com/PHPjc/628898.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628898.htmlTechArticleWe often use stripslashes and addslashes in php. Let me introduce in detail how to use stripslashes and addslashes. The difference between them. addslashes addslashes() function...
|
|