PHP几个数据处理函数

WBOY
Release: 2016-06-06 20:24:14
Original
1679 people have browsed it

最近在对前端表单输入数据进行处理中,遇到几个PHP字符串处理函数,真心搞不懂作用是什么,API说的太过于模糊,看不太懂,求大神帮忙解答一下区别和作用:

  • htmlspecialchars

  • addslashes

  • stripslashes

  • strip_tags

  • nl2br

  • mysql_real_escape_string

我就是想将textarea里的数据insert into进mysql数据库,用户可能输入html等乱七八糟的字符串,插入mysql,我应该怎么处理?

回复内容:

最近在对前端表单输入数据进行处理中,遇到几个PHP字符串处理函数,真心搞不懂作用是什么,API说的太过于模糊,看不太懂,求大神帮忙解答一下区别和作用:

  • htmlspecialchars

  • addslashes

  • stripslashes

  • strip_tags

  • nl2br

  • mysql_real_escape_string

我就是想将textarea里的数据insert into进mysql数据库,用户可能输入html等乱七八糟的字符串,插入mysql,我应该怎么处理?

标准写法(请忘掉那一堆乱七八糟的函数):

<code>//检查防止SQL注入的函数
function MySQLCheck(&$value)
{
    //去除斜杠(服务器配置给予的转义斜杠)
    if (get_magic_quotes_gpc())
    {
        $value = stripslashes($value);
    }
    //如果不是数字则加引号(专业的转义函数)
    if (!is_numeric($value))
    {
        $value = "'" . mysql_real_escape_string($value) . "'";
    }
    return $value;
    //示例用法:
    //$user = SQLCheck($_POST['user']);
    //$pwd = SQLCheck($_POST['pwd']);
    //$sql = "SELECT * FROM users WHERE user = $user AND password = $pwd";
}
</code>
Copy after login

函数来源(开源库):https://github.com/MoonLord-LM/MyPHP
另外,新版PHP已经废弃mysql扩展,推荐用mysqli扩展了,代码如下:

<code>//检查防止SQL注入的函数
function MySQLCheck(&$value)
{
    global $Connect;
    //去除斜杠(服务器配置给予的转义斜杠)
    if (get_magic_quotes_gpc())
    {
        $value = stripslashes($value);
    }
    //如果不是数字则加引号(专业的转义函数)
    if (!is_numeric($value))
    {
        $value = "'" . mysqli_real_escape_string($Connect,$value) . "'";
    }
    return $value;
    //示例用法:
    //$user = SQLCheck($_POST['user']);
    //$pwd = SQLCheck($_POST['pwd']);
    //$sql = "SELECT * FROM users WHERE user = $user AND password = $pwd";
}
</code>
Copy after login

上面的$Connect是数据库连接。
注意,这两个函数都是要在连接了MySQL数据库之后才能执行,否则会有报错。
另外,前端如果要展示,那么也要对script等等标签进行处理,可以用PHP的str_replace函数进行替换,还有

Copy after login
等等。
Related labels:
php
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!