【发布时间】:2015-09-30 17:05:16
【问题描述】:
我应该使用 PDO quote(),然后在检索用户输入时去掉引号和斜杠,还是有更好的方法?
当从 PHP 表单将用户输入插入 MySQL 时,任何单引号(撇号)都会截断数据。我目前正在使用 PDO 准备好的语句和 bindValue() 语句。我不确定是否使用 PDO quote() 方法,该方法似乎将我所有的字符串封装在引号中,然后用反斜杠(“\”)转义字符串中的引号。据我所知,如果我使用这种方法,那么我需要在检索数据时从字符串中去掉引号。这是最好的方法吗?使用 PDO quote() 然后使用子字符串删除封装的单引号是否安全?
另外,我有点困惑为什么单引号会截断数据输入。我认为 PDO bindValue() 应该为我转义单引号。我可能对此有误解。手册不是很详细。
我检查过的东西:
- PHP 魔术引号不在我的 php.ini 文件中,因为我正在使用一个版本,因为它已被贬值。
- 阅读 PDO 的所有手册(
bindParam()、bindValue()、prepare()、quote()) - 在 StackOverflow 上阅读所有类似问题。
这是我正在使用的 PDO 插入的代码:
//create query string
$profile_update_query_text = "
UPDATE user_profile
SET public=:public, headline=:headline, display_name=:display_name, skype=:skype, description=:description
WHERE user_id=:user_id";
//update table is required to modify existing user profile data
$query_profile_update_insert = $this->db_connection->prepare($profile_update_query_text);
$query_profile_update_insert->bindValue(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$query_profile_update_insert->bindValue(':public', $public, PDO::PARAM_INT);
$query_profile_update_insert->bindValue(':headline', $headline, PDO::PARAM_STR);
$query_profile_update_insert->bindValue(':display_name', $display_name, PDO::PARAM_STR);
$query_profile_update_insert->bindValue(':skype', $skype, PDO::PARAM_STR);
$query_profile_update_insert->bindValue(':description', $description, PDO::PARAM_STR);
//execute profile insert
$query_profile_update_insert->execute();
我还包括用于创建 PDO 连接的函数,因此可以验证我没有使用任何会导致问题的设置:
private function databaseConnection()
{
// connection already opened
if ($this->db_connection != null) {
return true;
} else {
// create a database connection, using the constants from config/config.php
try {
$this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
return true;
// If an error is catched, database connection failed
} catch (PDOException $e) {
$this->errors[] = MESSAGE_DATABASE_ERROR;
return false;
}
}
}
如果用户输入如下标题:
我是个滑雪高手
在 MySQL 中我得到:
我或“我是一个很棒的滑雪者”
取决于我是否使用 PDO quote()。
PDO bindParam() 的运行方式是否存在问题,它应该转义单引号,还是有更好的处理方法?
编辑——我检查了是否使用以下命令打开了魔术引号:
if(get_magic_quotes_gpc()){
echo "magic quotes on";
}else{
echo "magic quotes off";
}
【问题讨论】:
标签: php mysql pdo sql-injection