在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数据对象中了解更多信息. .
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屋!