简单的SQL注入示例
例如,A有一个银行网站。已为银行客户提供了一个网络界面,以查看其帐号和余额。您的银行网站使用http://example.com/get_account_details.php?account_id=102等网址从数据库中提取详细信息。
例如,get_account_details.php的代码如下所示。
$accountId = $_GET[ account_id $query = SELECT accountNumber, balance FROM accounts WHERE accountId = $accountId
客户accountId通过查询字符串作为account_id传递。与上面的Url一样,如果用户的帐户ID为102并且它在查询字符串中传递。Php脚本将创建如下所示的查询。
$query = SELECT accountNumber, balance FROM accounts WHERE accountId = 102
accountId 102获取accountNumber和余额详细信息,并提供给客户。
我们假设另一个场景,智能客户已经通过了account_id,就像0 OR 1=1查询字符串一样。现在会发生什么?PHP脚本将创建如下所示的查询并在数据库上执行。
$query = SELECT accountNumber, balance FROM accounts WHERE accountId = 0 OR 1=1
查看由脚本和数据库返回的结果创建的查询。您可以看到此查询返回了所有帐号和可用余额。
这称为SQL注入。这是一个简单的方式,其实可以有很多方法来进行SQL注入。下面我们就来看一下如何使用PHP MySQLi驱动程序和PHP PDO驱动程序防止SQL注入。
使用PHP-MySQLi驱动程序
可以使用PHP-MySQLi驱动程序预处理语句来避免这些类型的SQL注入。
PHP防止SQL注入的代码如下:
$accountId = $_GET[ account_id if ($stmt = $mysqli- prepare( SELECT accountNumber, balance FROM accounts WHERE accountId = ? )) { $stmt- bind_param( s , $accountId); $stmt- execute(); $result = $stmt- get_result(); while ($row = $result- fetch_assoc()) { // do something here $stmt- close(); }
使用PHP-PDO驱动程序
可以使用PHP-PDO驱动程序prepare语句来避免这些类型的SQL注入。
PHP解决上面的SQL注入问题的代码如下:
$accountId = $_GET[ account_id if ($stmt = $pdo- prepare( SELECT accountNumber, balance FROM accounts WHERE accountId = :accountId )) { $stmt- execute(array( name = $name)); foreach ($stmt as $row) { // do something here $stmt- close(); }
本篇文章到这里就已经全部结束了,更多其他精彩内容大家可以关注php 的其他相关栏目教程!!!
以上就是如何在PHP中防止SQL注入的详细内容,PHP教程
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。
新闻热点
疑难解答