gpt4 book ai didi

php - 如何用 PDO::quote() 替换 mysql_escape_string

转载 作者:行者123 更新时间:2023-11-29 06:56:09 24 4
gpt4 key购买 nike

我正在使用 http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/ 学习 PHP到目前为止,这非常有用,但我无法去替换已弃用的 mysql_escape_string

我关注了 StackOverFlow 上的现有对话: https://stackoverflow.com/a/20294502/7157496我认为一个可能的解决方案是将 quote() 实现为 $conn->quote($order) 以避免 SQL 注入(inject),但我不知道它应该在代码中发挥作用。

或者您认为 $st = $conn->prepare( $sql ); 已经在这里完成了这项工作吗?

  public static function getList( $numRows=1000000, $order="publicationDate DESC" ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

/*$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles
ORDER BY " . mysql_escape_string($order) . " LIMIT :numRows";*/

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles
ORDER BY " . $order . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();

while ( $row = $st->fetch() ) {
$article = new Article( $row );
$list[] = $article;
}

最佳答案

所以你的问题是 PDO 只允许绑定(bind)值并使用 PDO::Quote不是一种安全的替代方案,也不是一种有效的替代方案。

Or do you think that $st = $conn->prepare( $sql ); is already doing the job here?

不,它不做这项工作,PDO::prepare 只准备绑定(bind)值,而不是硬编码值。

因为您的 $order 正在获取用户的输入(很容易被操纵),所以最安全的选择是创建一个允许的白名单订单类型数组。如果来自 $order 的输入位于白名单数组中,您就可以继续准备并执行该语句。

编辑:考虑到评论中的链接,这是我对当前代码的替代方案:

<?php
public static function getList( $numRows=1000000, $order="publicationDate DESC" ) {

$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);

//Your whitlelist of order bys.
$order_whitelist = array("publicationDate DESC", "publicationDate ASC", etc..);

// see if we have such a name, if it is not in the array then $order_check will be false.
$order_check = array_search($order, $order_whitelist);

if ($order_check !== FALSE)
{

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles
ORDER BY " . $order . " LIMIT :numRows";

$st = $conn->prepare($sql);
$st->bindValue(":numRows", $numRows, PDO::PARAM_INT);
$st->execute();
$list = array();

while ($row = $st->fetch())
{
$article = new Article($row);
$list[] = $article;
}
}

关于php - 如何用 PDO::quote() 替换 mysql_escape_string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45521453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com