In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?(在 PHP 中向数据库提交字符串时,我应该使用 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.
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));
Or a little more self explaining:
$dbPreparedStatement = $db->prepare('INSERT INTO table (htmlcontent) VALUES (:htmlcontent)');
$dbPreparedStatement->execute(array(':htmlcontent' => $yourHtmlData));
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();
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() 处理非法字符还是使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 PHP 中向数据库提交字符串时,我应该使用 htmlspecialchars() 处理非法字符还是使用正则表达式?
基础教程推荐
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01