如何防止 XSS 和 SQL 注入 [英] How to prevent against XSS and SQL injection

查看:38
本文介绍了如何防止 XSS 和 SQL 注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查我的用户数据是否存在 XSS 和 SQL 注入,这就是我尝试的方式

i want to check my data from the user for XSS and SQL injection and this is how i tried

if (isset($_GET['membernumber'])) 
{
    $mem = htmlentities($_GET['membernumber']);
    $memberparamter = cleanData($mem);

}

但是哪种方法是最好/正确的检查方法?

But which method is the best/correct way to check?

方法一

function cleanData($data)
    {
        $data=mysql_real_escape_string($data);
        $data=trim($data);
        $data=stripcslashes($data);
        $data=htmlspecialchars($data);
        $data=strip_tags($data);
        return $data;
    }

方法二

function cleanData($data)
    {
        $data=mysql_real_escape_string($data);
        $data=trim($data);
        $data=strip_tags($data);
        return $data;
    }

方法三

htmlspecialchars(stripcslashes(trim($data)))

推荐答案

如前所述,准备好的语句是防止 SQL 注入的最佳方法之一.即,您不应将参数添加为最终查询字符串的一部分.您应该使用参数占位符,并通过键/值数组添加参数.

As mentioned, prepared statements are one of the best ways to prevent SQL injections. i.e., you shouldn't add your parameters as part of the final query string. You should use parameter placeholders, and add the parameters via a key/value array.

如果您使用 PDO,请查看此页面,其中更详细地描述了准备好的语句:

If you're using PDO, have a look at this page, which describes prepared statements in greater detail:

http://php.net/manual/en/pdo.prepared-statements.php

可以在此处找到对 PHP 输入过滤器的详尽解释(以及一篇关于清理的好文章):

A quite thorough explanation of PHP's input filters (and a good article on sanitization) can be found here:

http://coding.smashingmagazine.com/2011/01/11/keeping-web-users-safe-by-sanitizing-input-data/

在此处查看 PHP 自己的过滤器/清理功能:

Check here for PHP's own filters/sanitization functions:

http://www.php.net/manual/en/filter.filters.php

您可能对 filter_var 和 filter_input 函数感兴趣:

You are probably interested in the filter_var and filter_input functions:

另外,这个问题有一些很好的提示:使用 PHP 清理用户输入的最佳方法是什么?

Also, this question has some good pointers: What's the best method for sanitizing user input with PHP?

这个问题也有很好的提示:什么是最好的 PHP 输入清理函数?

This question has very good pointers too: What are the best PHP input sanitizing functions?

这篇关于如何防止 XSS 和 SQL 注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆