hehexu

博客园 首页 新随笔 联系 订阅 管理

php addslashes函数的作用是在预定义的字符前面加上反斜杠,这些预定义字符包括:

  • 单引号(')
  • 双引号(")
  • 反斜杠(\)
  • NULL

addslashes函数经常使用在向数据库插入数据时,比如有一个字符串

$str="my name's wxp";

现在要将这个字符串插入到数据库表中,由于该字符串有单引号',这样很可能与mysql拼接字符串的单引号'冲突,导致SQL语句不正确,也就无法正常执行插入操作,此时我们需要使用addslashes函数处理这个字符串。如:

$str="my name's wxp";
echo addslashes($str);//输出my name\'s wxp

然后在拼接mysql字符串:

$sql="insert into student(student_name)values('".addslashes($str)."')";
mysql_query($sql);

此时字符串被插入到数据库,那么大家是否知道插入的字符串是带反斜杠还是不带反斜杠呢?恐怕很多人都会认为肯定是带反斜杠的字符串。其实这个答案是错误的,插入的字符串是没有带反斜杠。至于为什么插入的字符串在数据库中是没有加反斜杠,请大家继续看下面讲解。

 

如果字符串$str="my name's wxp"是使用POST和GET提交的数据,这个时候插入数据库中的数据是带反斜杠的,由此可知addslashes只是在POST和GET数据插入数据库时才会把反斜杠同时插入到数据库,其他情况下不会将反斜杠插入到数据库。

 

if(!function_exists("sanitize")){
function sanitize($string,$stripall=true){
// Convert null to empty string
if ( is_null($string) ) {
$string = "";
}

// Trim any leading or trailing whitespace
$clean=trim($string);

// Convert any special characters to their normal parts
$clean=html_entity_decode($clean,ENT_COMPAT,"UTF-8");

// By default strip all html
$allowedtags=($stripall)?'':'<a><b><i><img><u><br>';

// Strip out the shit we don't allow
// 从字符串中去除 HTML 和 PHP 标记
//$allowedtage 允许 保留的html标记

$clean=strip_tags($clean, $allowedtags);
// If we decide to strip double quotes instead of encoding them uncomment the
// next line
// $clean=($stripall)?str_replace('"','',$clean):$clean;
// What is this gonna do ?


//HTML 转义字符 '"<>& 以及 ASCII 值小于 32 的字符。
$clean=filter_var($clean, FILTER_SANITIZE_SPECIAL_CHARS);

// There shoudln't be anything left to escape but wtf do it anyway

$clean=addslashes($clean);

return $clean;
}
}

 

posted on 2018-03-01 23:46  hehexu  阅读(356)  评论(0编辑  收藏  举报