Escape functions commonly used in PHP

  • 2021-01-19 22:02:51
  • OfStack

1. addslashes

addslashes is used to escape special characters in SQL statements, including ('), ("), (), (), (NUL). This function is used when DBMS does not have its own escape function, but if DBMS does have its own escape function, it is recommended to use the original function. For example, MySQL has the function mysql_real_escape_string to escape SQL. Note that magic_quotes_gpc is enabled by default before PHP5.3, which is used to perform addslashes operations on $GET, $POST, and $COOKIE, so there is no need to repeat the call to addslashes on these variables, otherwise it will be es24EN. magic_quotes_gpc is deprecated in PHP5.3, and has been removed since PHP5.4. If you use the latest version of PHP, you don't have to worry about this. stripslashes is the unescape function of addslashes.

2. htmlspecialchars

HTML (HTML, Entity, HTML) & xxxx;) Forms, including ( & ), ('), ("), ( < ),( > )5 characters.

& (AND) = > & amp;
"(double quotation marks) = > & quot; When ENT_NOQUOTES is not set
'(single quotation marks) = > & # 039; (when ENT_QUOTES is set)
< (less than sign) = > & lt;
> (greater than sign) = > & gt;
htmlspecialchars can be used to filter $GET, $POST, $COOKIE data to prevent XSS. Note that the htmlspecialchars function only escapes HTML characters that are considered unsafe. If you want to escape all possible HTML characters, use htmlentities. htmlspecialchars_decode is an decode function of htmlspecialchars.

3. htmlentities

htmlentities Escapes what can be escaped in HTML to HTML Entity. html_entity_decode is an decode function of htmlentities.

4. mysql_real_escape_string

mysql_real_escape_string calls mysql_real_escape_string to escape (\x00), (\n), (\r), (), ('), (\x1a) by adding a backslash () in front of it to prevent SQL injection. Note that you do not need to call stripslashes to perform unescape when reading data from the database, because the backslashes are added to the database when SQL is executed. The backslashes are removed when data is written to the database, so the content written to the database is the original data, and there is no backslash in front of it.

5. strip_tags

strip_tags will filter out NUL, HTML and PHP tags.

6. Conclusion

XSS is not completely avoided by PHP's built-in security functions. It is recommended to use HTML


Related articles: