php - 如何正确清理 html post 以保存在 mysql 中

标签 php mysql blogs sanitization

我正在尝试创建一个博客系统,我想将博客文章数据保存到 mysql 中,但我不太清楚如何清理或清理数据,这就是我尝试过的

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  return $data;
}

现在,当我通过 ajax 发布博客数据时,它看起来像

<h1 class="text-center">
    Write the titles of article here
</h1>

然后我清理帖子数据并回显它

echo $title = mysqli_real_escape_string($connecDB, test_input($_POST['page__title']));

然后这是我得到的回复

\r\n    Write the titles of article here\r\n

我想知道为什么我在响应中收到这些\r\n 我怎样才能摆脱它们,这是清理 html 帖子的最佳方法

注意:我想将数据保存为mysql中的html

我已经有一个正则表达式,可以找到样式和脚本标签并删除它,我也尝试删除条斜线并尝试添加 strip_tags ,但我仍然得到\r\n

最佳答案

您会得到\r\n,因为mysql_real_escape_string()用相应的转义序列替换控制字符。此函数仅适用于将变量替换为 MySQL 查询时,不应用于以 HTML 形式输出。清理 HTML 输出的正确函数是 htmlentities()

$title = test_input($_POST['page__title']);
echo htmlentities($title);

如果您想在输出中保留换行符,还应该使用nl2br()

echo nl2br(htmlentities($title));

关于php - 如何正确清理 html post 以保存在 mysql 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37980690/

相关文章:

php - 从多维数组php中检索值

mysql - Zend 框架 : How to download file from mySql Blob field

drupal - 如何为 Drupal 创建 RSS 源?

javascript - 将数据存储在 "blog"风格的系统中

iphone - 图像存储在 RSS 中?

php - 在迁移 laravel 5.1 中设置自动增量字段从 1000 开始

php - opencart 支付网关

php - 在 php 中使用选定的答案保存 id

php - Codeigniter 分页显示太多链接

mysql - 如果存在则插入