在 PHP 中向数据库提交字符串时,我应该使用 htmlspecialchars() 还是使用正则表达式处理非法字符? [英] In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?
问题描述
我正在处理一个表单,用户可以在要提交给数据库的字符串中使用非法/特殊字符.我想转义/否定字符串中的这些字符,并且一直在使用 htmlspecialchars().但是,有没有更好/更快的方法?
I am working on a form with the possiblity for the user to use illegal/special characters in the string that is to be submitted to the database. I want to escape/negate these characters in the string and have been using htmlspecialchars(). However, is there is a better/faster method?
推荐答案
如果您将此数据提交到数据库,请查看您的数据库的转义函数.
If you submit this data to the database, please take a look at the escape functions for your database.
也就是说,对于 MySQL,有 mysql_real_escape_string.
That is, for MySQL there is mysql_real_escape_string.
这些转义函数会处理任何可能是恶意的字符,并且您仍然会以与放入其中的方式相同的方式获取数据.
These escape functions take care of any characters that might be malicious, and you will still get your data in the same way you put it in there.
您还可以使用准备好的语句来处理数据:
You can also use prepared statements to take care of the data:
$dbPreparedStatement = $db->prepare('INSERT INTO table (htmlcontent) VALUES (?)');
$dbPreparedStatement->execute(array($yourHtmlData));
或者多一点自我解释:
$dbPreparedStatement = $db->prepare('INSERT INTO table (htmlcontent) VALUES (:htmlcontent)');
$dbPreparedStatement->execute(array(':htmlcontent' => $yourHtmlData));
如果要保存不同类型的数据,可以使用bindParam
来定义每种类型,即一个整数可以定义为:$db->bindParam(':userId', $userId, PDO::PARAM_INT);
.示例:
In case you want to save different types of data, use bindParam
to define each type, that is, an integer can be defined by: $db->bindParam(':userId', $userId, PDO::PARAM_INT);
. Example:
$dbPreparedStatement = $db->prepare('INSERT INTO table (postId, htmlcontent) VALUES (:postid, :htmlcontent)');
$dbPreparedStatement->bindParam(':postid', $userId, PDO::PARAM_INT);
$dbPreparedStatement->bindParam(':htmlcontent', $yourHtmlData, PDO::PARAM_STR);
$dbPreparedStatement->execute();
其中 $db
是您的 PHP 数据对象 (PDO).如果您不使用它,您可以在 PHP 数据对象 中了解更多相关信息em>.
Where $db
is your PHP data object (PDO). If you're not using one, you might learn more about it at PHP Data Objects.
这篇关于在 PHP 中向数据库提交字符串时,我应该使用 htmlspecialchars() 还是使用正则表达式处理非法字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!