一、函数功能:
数据库查询语句的要求,在单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符) 等特殊字符前添加反斜杠。它是stripslashes()函数的反向操作函数。
二、函数语法:string addslashes($str)
三、函数参数:参数描述
$str要为特殊字符添加反斜杠的元素字符串。
四、返回值:返回添加反斜杠完成的字符串。
五、用法举例:
1、基本用法:<?php
# 爱E族:aiezu.com
echo addslashes("it's\n");
echo addslashes('abc"def\123');输出:it\'s
abc\"def\\123
2、给Sql查询参数添加反斜杠:<?php
# 爱E族:aiezu.com
#未使用addslashes函数添加反斜杠的SQL语句
$title = "it's";
$sql = "select * from Table where title='{$title}'";
echo '$sql值为: ' . $sql;
echo "\n\n";
#使用addslashes函数添加反斜杠的SQL语句:
$title = addslashes("it's");
$sql = "select * from Table where title='{$title}'";
echo '$sql值为: ' . $sql;输出:$sql值为: select * from Table where title='it's'
$sql值为: select * from Table where title='it\'s'注:上面一条SQL语句由于"it's"的单引号导致SQL中的title查询值闭合单引号提前闭合,而导致如下错误:
PHP Fatal error: Uncaught exception 'Exception' with message 'MySQL Query Error : You have an error in your SQL syntax; check the manual that corresponds to your Mysql server version for the right syntax to use near 's'' at line 1
SQL:select * from Table where title='it's'' in /tmp/mysql.php:148
3、对数组元素使用addslashes:<?php
# 爱E族:aiezu.com
function array_addslashes( $array ){
if(is_array($array) ){
foreach($array as $key=>&$value){
$value=array_addslashes($value);
}
return $array;
}else{
return addslashes($array);
}
}
$arr = array(
'aa'=>"O'Reilly"
,'ab'=>array(
'ba'=>"It's"
,'bb'=>"Is't a book?"
)
);
$arr = array_addslashes($arr);
print_r($arr);输出:Array
(
[aa] => O\'Reilly
[ab] => Array
(
[ba] => It\'s
[bb] => Is\'t a book?
)
)
4、对浏览器发送到http服务器的数据进行addslashes转义:
当php.ini配置文件中magic_quotes_gpc配置项值为On时,浏览器发送到服务器的数据($_POST, $_GET, $_COOKUE)会自动进行addslashes转义,无需再次进行addslashes转义(PHP 5.4 之前 magic_quotes_gpc 默认是 On)。我们可以通过get_magic_quotes_gpc函数检测magic_quotes_gpc配置项值是否为On:<?php
# 爱E族:aiezu.com
function array_addslashes( $array ){
if(is_array($array) ){
foreach($array as $key=>&$value){
$value=array_addslashes($value);
}
return $array;
}else{
return addslashes($array);
}
}
if ( ! get_magic_quotes_gpc() ) {
$_POST = array_addslashes($_POST);
$_GET = array_addslashes($_GET);
$_COOKIE= array_addslashes($_COOKIE);
}