回复内容: 在网上看了些关于防止sql注入的文件和提问,比如使用预处理、过滤敏感字符。我一直想不明白的是,解决ssql注入问题非常非常简单啊,只要对用户输入的内容转义一下就可以了,就是讲用户输入的',转义成\',\就可以了,搞不懂为什么搞的那么复杂了?还是说我这种方法不能杜绝所有的sql注入
用htmlspecialchars/htmlpurifier防御xss注入,用预处理参数化查询防御sql注入.
调用htmlpurifier过滤xss后输出html:
require dirname(__file__).'/htmlpurifier/library/htmlpurifier.auto.php';$purifier = new htmlpurifier();echo $purifier->purify($html);
mysqli绑定参数查询:
$db = @new mysqli();$stmt = $db->prepare('select * from posts where id=?'); //预处理$stmt->bind_param('i', $id); //绑定参数$stmt->execute(); //查询var_export($stmt->get_result()->fetch_all());
wireshark里用tcp.port==3306过滤分析php和mysql通信
set_charset('utf8');$stmt = $mysqli->prepare(select `username` from `pb_users` where `id`=?);$stmt->bind_param('i', $id);$stmt->execute();$stmt->store_result();$stmt->bind_result($username);while ($stmt->fetch()) echo $username;$stmt->close();$mysqli->close();query('set names utf8');$dbh->setattribute(pdo::attr_emulate_prepares, false);$sth = $dbh->prepare(select `username` from `pb_users` where `id`=?);$sth->bindparam(1, $id, pdo::param_int);$sth->execute();print_r($sth->fetchall(pdo::fetch_assoc));$sth = null;$dbh = null;
在 request prepare statement 里可以看到 select username from pb_users where id=?
在 request execute statement 里可以看到 parameter 内容为:
type: field_type_longlong (8)
unsigned: 0
value: 1
可见php将sql模板和变量分两次发送给mysql,由mysql完成变量的转义处理.
既然sql模板和变量是分两次发送的,那么就不存在sql注入的问题了.
在mysql的general_log里可以看到:
prepare select username from pb_users where id=?
execute select username from pb_users where id=1
如果id绑定为string,则execute时id赋值是这样的: id='1'
如果pdo没有关闭模拟预处理,则可以看到:
query select username from pb_users where id=1
解决注入,还是pdo来的比较彻底,最不济也得mysqli,上bind,加类型.
只要对用户输入的内容转义一下就可以了,就是讲用户输入的',转义成\',\就可以了,搞不懂为什么搞的那么复杂了?还是说我这种方法不能杜绝所有的sql注入
你一定不知道有一种注入叫做宽字符注入,int型注入,orderby注入,
其次注入其实非常容易防御,主要麻烦的是xss
