本篇文章将给大家介绍关于php中的sql注入以及使用php-mysqli和php-pdo驱动程序防止sql注入的方法。下面我们来看具体的内容。
简单的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中防止sql注入的详细内容。