Addslashes
The addslashes () function adds a backslash before the specified predefined character.
The predefined characters are:
• Single quotes (')
• Double quotation marks (")
• Backslash ()
• NULL
In this example, we want to add a backslash to the predefined characters in the string:
Note: When the command is on, the PHP command magic_quotes_gpc automatically runs addslashes () on all GET, POST, and COOKIE data (). Do not use addslashes () for strings that have been escaped by magic_quotes_gpc, because this causes double-layer escape. In this case, you can use the get_magic_quotes_gpc () function for detection.
The code is as follows: |
Copy code |
/** * Determine whether to use addslashes () for processing * * @ 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 ); Break; } } Else { Switch ($ db_type ){ Case "mysql ": $ Str = addslashes ($ str ); Break; Case "access ": $ Str = str_replace ("'", "'' ", $ str ); Break; } } Return $ str; } |
Custom function str_addslashes description: If you do not know whether magic_quotes_gpc is enabled during the submission process, you can use this method. If you are on, the mysql database will not process it, however, the access database must be removed first, and then the single quotation marks must be replaced with double quotation marks. When it is off, add the mysql database
Stripslashes ()
The stripslashes () function deletes the backslash added by the addslashes () function.
Example
Code
The code is as follows: |
Copy code |
// Submit data or prepare variables: $ Content = addslashes ("This is data, no matter whether there are single quotes or variables "); // Insert data to the database. The code is omitted. // Start displaying data $ Content = "data read from the database "; If (get_magic_quotes_gpc ()){ $ Content = stripslashes ($ Content ); } Echo $ Content; |
Difference summary
When magic_quotes_gpc = On, data processed using addslashes () will be saved in the database as '. If the data is output directly at this time, the stripslashes () can be removed (different from str_replace ("," ", $ Str) because it has more content than you expected )).
When magic_quotes_gpc = Off, the data processed with addslashes () will be saved in the database in the form of '. There is no problem mentioned above, addslashes () it does not cause data insertion errors. If data is output directly at this time, the data is normal. You do not need to use stripslashes ().
Addslashes () and stripslashes () are the opposite. Direct memory: add addslashes (), and remove stripslashes ().