1、addslashes ( string ):
在预定义字符:(1)单引号('),(2)双引号("),(3)反斜杠(\),(4)NULL 前加入 ' \ '
<!DOCTYPE html>
<html>
<body>
<?php
$str = "Who's Peter Griffin?";
echo $str . " This is not safe in a database query.<br>";
echo addslashes($str) . " This is safe in a database query.";
?>
</body>
</html>
输出为:
Who's Peter Griffin? This is not safe in a database query.
Who\'s Peter Griffin? This is safe in a database query.
2、stripslashes(string): 删除反斜杠
<!DOCTYPE html>
<html>
<body>
<?php
echo stripslashes("Who\'s Peter Griffin?");
?>
</body>
</html>
输出是:
Who's Peter Griffin?
3、mysqli_real_escape_string(conn, string):转义在 SQL 语句中使用的字符串中的特殊字符
<?php
// 假定数据库用户名:root,密码:123456,数据库:RUNOOB
$con=mysqli_connect("localhost","root","123456","RUNOOB");
if (mysqli_connect_errno($con))
{
echo "连接 MySQL 失败: " . mysqli_connect_error();
}
mysqli_query($con,"CREATE TABLE websites2 LIKE websites");
$newname="菜鸟'教程";
// 没有转义 $newname 中特殊字符,执行失败
mysqli_query($con,"INSERT into websites2 (name) VALUES ('$newname')");
// 转义特殊字符
$newpers=mysqli_real_escape_string($con,$newname);
// 转义后插入,执行成功
mysqli_query($con,"INSERT into websites2 (name) VALUES ('$newpers')");
mysqli_close($con);
?>
4、mysqli_real_escape_string():转义在 SQL 语句中使用的字符串中的特殊字符
NULL(ASCII 0)、\n、\r、\、'、"、\x00、\x1a 和 Control-Z
<?php
// 假定数据库用户名:root,密码:123456,数据库:RUNOOB
$con=mysqli_connect("localhost","root","123456","RUNOOB");
if (mysqli_connect_errno($con))
{
echo "连接 MySQL 失败: " . mysqli_connect_error();
}
mysqli_query($con,"CREATE TABLE websites2 LIKE websites");
$newname="菜鸟'教程";
// 没有转义 $newname 中特殊字符,执行失败
mysqli_query($con,"INSERT into websites2 (name) VALUES ('$newname')");
// 转义特殊字符
$newpers=mysqli_real_escape_string($con,$newname);
// 转义后插入,执行成功
mysqli_query($con,"INSERT into websites2 (name) VALUES ('$newpers')");
mysqli_close($con);
?>
5、magic_quote_gpc:魔术引号开关,若为 on 状态,会对数据中含单引号(’)、双引号(”)、反斜线(\)与 NULL(NULL 字符)等字符加上反斜线;
6、get_magic_quotes_gpc():返回一个 bool 值,若为 true,说明magic_quote_gpc处于 on 状态,反之,则为 off 状态;
7、preg_quote(string, delimiter):用于转义正则表达式的特殊字符
(1)string: 输入字符串;
(2)delimiter: 如果指定了可选参数 delimiter,它也会被转义。这通常用于 转义 PCRE 函数使用的分隔符。 (/ 是最通用的分隔符);
eg1:
<?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords;
?>
输出为:
\$40 for a g3\/400
eg2:
<?php
//在这个例子中,preg_quote($word) 用于保持星号原文涵义,使其不使用正则表达式中的特殊语义。
$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/" . preg_quote($word) . "/",
"<i>" . $word . "</i>",
$textbody);
echo $textbody;
?>
输出为:
This book is <i>*very*</i> difficult to find.