首页 > php开发 > php中stripslashes与addslashes用法区别

php中stripslashes与addslashes用法区别

在php中我们常会使用到stripslashes与addslashes了, 下面我来详细的介绍stripslashes与addslashes使用方法与它们之间的区别.

addslashes

addslashes() 函数在指定的预定义字符前添加反斜杠.

这些预定义字符是:

•单引号 (')

•双引号 (")

•反斜杠 ()

•NULL

在本例中,我们要向字符串中的预定义字符添加反斜杠:

注释:默 认情况下,PHP 指令 magic_quotes_gpc 为 on,对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes().不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes(),因为这样会导致双层转义.遇到这种情况时可以使用函数 get_magic_quotes_gpc() 进行检测.

实例代码:

<?php
/** 
 * 判断是否用addslashes()处理
 *
 * @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;
}
?>

自定义函数str_addslashes说明:如果我们在提交过程中不知道magic_quotes_gpc是否打开的情况下,可采取如此方式进行处理,为on时mysql数据库不做处理,而access数据库依然要先去掉,再将单引号替换为双引号.为off时mysql数据库加上

stripslashes()

stripslashes() 函数删除由 addslashes() 函数添加的反斜杠.

实例代码:

//提交数据,或者变量准备: 
$Content=addslashes("这里面是数据,不管有没单引号或者还是变量"); 
//插入数据到数据库,代码省略 
//开始显示数据 
$Content="从数据库读取的数据"; 
if(get_magic_quotes_gpc()){ 
  $Content=stripslashes($Content);  
} 
echo $Content;

区别总结

当magic_quotes_gpc = On时,使用了addslashes()处理后的数据在数据库中将以'形式保存,如果此时直接输出的话,就会发现比自己期待的内容多了个,因此stripslashes()出场了,它能把去掉(区别于str_replace("", "",$Str)).

当magic_quotes_gpc = Off时,使用了addslashes()处理后的数据在数据库中将以'形式保存,没有上面说的有的问题,addslashes()起到插入数据不出错的作用,如果此时直接输出的话,数据正常.不需要再用stripslashes().addslashes()和stripslashes()正好是相反的,直接记忆:addslashes()加个,stripslashes()去个


本文地址:http://www.phprm.com/develop/fs2127.html

转载随意,但请附上文章地址:-)

标签:stripslashes addslashes

相关文章

发表留言