PHP特殊字符如反斜杠处理函数addslashes()和stripslashes()的用法

WBOY
Release: 2016-06-20 13:03:20
Original
1151 people have browsed it

PHP自带的库函数 addslashes() 和 stripslashes() 都属于字符串处理类函数,作用正好相反:

addslashes():对输入字符串中的某些预定义字符前添加反斜杠,这样处理是为了数据库查询语句等的需要。这些预定义字符是:单引号 (') ,双引号 (") ,反斜杠 (\) ,NULL。

stripslashes():删除由 addslashes() 函数添加的反斜杠。该函数用于清理从数据库或 HTML 表单中取回的数据。(若是连续二个反斜杠,则去掉一个,保留一个;若只有一个反斜杠,就直接去掉。)

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

if (get_magic_quotes_gpc()){
      code....
}
Copy after login

addslashes() 例子:

<?php
$str = "Who&#39;s John Adams?";
echo $str . " This is not safe in a database query.<br />";
echo addslashes($str) . " This is safe in a database query.";
?>
Copy after login

输出:

Who's John Adams? This is not safe in a database query.
Who\'s John Adams? This is safe in a database query.

stripslashes() 例子:

<?php
echo stripslashes("Who\&#39;s John Adams?");
?>
Copy after login

输出:

Who's John Adams?


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!