使用换行符安全地存储文本区域输入并保留换行符


Safely store textarea input with newlines and preserve linebreaks

我在数据库中将用户提交的演示文稿作为文本字段存储时遇到问题。它不允许任何 HTML,但应保留换行符

因此,例如,如果用户使用文本区域作为输入法从表单提交这样的演示文稿:

这是第 1 行

这是第 3
行这是第 4 行

它应该完全像这样输出,并清除过程中任何HTML的输入。

存储过程:

   if (isset($_POST['presentation'])) {
        $presentation = $purifier->purify($_POST['presentation']);
        $presentation = $mysqli->real_escape_string($presentation);
        if (strlen($presentation) > 1000) {
            return 2;
        }
    }
    else {
        $presentation = null;
    }
    if ($update_stmt = $mysqli->prepare("UPDATE user SET user_presentation = ?
                                         WHERE user_id = ?")) {
        $update_stmt->bind_param('ss', $presentation, $user_id);
    }
    if ($update_stmt->execute() == false) {
        $success = 0;
    }
    $update_stmt->close();

并在获取后输出:

<p><?php echo nl2br($profile['presentation']); ?></p>    

它在数据库中存储如下:

This is line 1'r'n'r'nThis is line 3'r'nThis is line 4

并在页面上显示为:

This is line 1rnrnThis is line 3rnThis is line 4

我想要的是显示用户提交的演示文稿,并保留换行符,清除任何 HTML 并安全地存储在数据库中。

我已经尝试过strip_tags,条形斜杠等,但我仍然无法让它工作。

有人可以帮忙吗?

提前谢谢。

在通过 nl2br() 传递字符串之前,您可以使用 str_replace 将它们转换为各自的转义序列。 这是一个示例:

$profile = nl2br(str_replace('''r''n', "'r'n", $profile['presentation']));