PHP 关于SQL注入的防范措施。

php.cn
Release: 2016-06-23 13:42:19
original
973 people have browsed it

    最近在使用框架的时候还是有点不安,不知道框架的设计者有没有考虑到SQL-Injection的问题,我在顶层需不需要做一些必要的过滤等等,由此我特意的去StackOverflow看了下,真是获益良多,然后我去看了下框架的DB库的内部方法,然后就比较安心了。分享下国内外PHP程序员在处理SQL-Injection的一些方案。


    国外普遍都推荐,只要你是使用查询都应该做到两点:1.prepared statements(准备好的声明) 2.parameterized queries (参数化的查询请求)

我一开始也不理解这个是什么意思,后来看他们举例就大概知道了。比较安全的SQL,你需要一开始对查询的变量进行准备。如:

$name = $_POST['name'];$sql = 'select * from user where name'.$name;
Copy after login

那么最好就是对$name先处理下,

$name = mysql_real_escape_string($_POST['name']);
Copy after login

然后,让请求过来的变量成为参数,而不是SQL语言本身。

$sql = 'select * from user where name=\''.$name.'\'';
Copy after login

当然,这种写法还是比较粗糙。

所以,一般都会推荐使用PDO 或者是MYSQLI的prepare() excute()方法。

$stmt = $pdo->prepare('SELECT * FROM user WHERE name = :name');$stmt->execute(array('name' => $name));
Copy after login

关于PDO::prepare()

这样做的好处就是,你不再需要担心查询请求会插入一些SQL语句,因为这些语句都将会当作是请求变量(一个字符串或者是数字),不再会误以为是SQL语言本身。这样可以大大的减少SQL注入的机会。

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 [email protected]
Latest issues
Popular Tutorials
More>
Latest downloads
More>
web effects
Website source code
Website materials
Front end template
About us Disclaimer Sitemap
PHP Chinese website:Public welfare online PHP training,Help PHP learners grow quickly!