PHP 字符串存储(转义) addslashes 与 stripslashes 函数

来源:互联网 发布:mac 终端 上传文件 编辑:程序博客网 时间:2024/04/28 01:20

原文链接

PHP 字符串存储(转义)

PHP 的字符串向数据库进行写入时,为避免数据库错误,需要对特殊字符进行转义(字符前加上 符号)。如 O'reilly 转义成 O'reilly,这样可以将数据放入数据库中,而不会插入额外的 。

这些特殊字符包括:单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)。

addslashes()

addslashes() 函数用于对特殊字符加上转义字符,返回一个字符串。

语法:

string addslashes ( string string )

例子:

<?php$str = "Is your name O'reilly?";echo addslashes($str);// 输出:Is your name O\'reilly??>

提示

默认情况下,PHP 指令 magic_quotes_gpc 为 on,系统会对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes() 。不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes() ,因为这样会导致双层转义。

可以对 get_magic_quotes_gpc() 进行检测以便确定是否需要使用 addslashes() :

<?phpif (!get_magic_quotes_gpc()) {    $lastname = addslashes($_POST['lastname']);} else {    $lastname = $_POST['lastname'];}echo $lastname;//转义后的字符如:O'reilly?>

stripslashes()

该函数为 addslashes() 的反函数,返回一个字符串。

语法:

string stripslashes ( string string )

例子:

<?php$str = "Is your name O\'reilly?";echo stripslashes($str);// 输出:Is your name O'reilly??>

阅读全文
0 0
原创粉丝点击