清理输出数据

问题描述 投票:0回答:1

我在代码中使用带有准备好的语句的PDO,并且我想知道如何更好地输出数据,因为我也在使用WYSIWYG编辑器。使用strip_tags,htmlentities或htmlspecialchars无法正确显示文本样式。

这里是将数据输入数据库的代码:

$sql    = "INSERT INTO posts(post_title, post_content, post_author, post_category, post_tags, post_image)";
                $sql   .= "VALUES(:title, :content, :author, :category, :tags, :image)";
                $stmt   = $dbConn->prepare($sql);
                $result = $stmt->execute([
                    ':title'    => $postTitle,
                    ':content'  => $postContent,
                    ':author'   => $postAuthor,
                    ':category' => $postCategory,
                    ':tags'     => $postTags,
                    ':image'    => $imageFullName
                ]);
php strip-tags
1个回答
0
投票

您要求的此内置功能将很难获得。他们有很多解决方法

1。)您可以像htmlpurifier这样使用外部库http://htmlpurifier.org/

[2。)使用strip_tags()

您可以使用strip_tags()允许通过某些标签,同时去除其他html危险标签

例如,在去除其他标签时仅允许<h1> and <b>,您可以执行此操作

$text_strip = '<h1>Am nancy.</h1><div>hhhh</div> <b>Mooree</b> <a href="">remove me</a>';
// Allow only <h1> and <a>
echo strip_tags($text_strip , '<h1><b>');

请参阅可用数据过滤方法列表data filtering: https://www.php.net/manual/en/book.filter.php

3。)使用FILTER_SANITIZE_STRING()

您也可以使用FILTER_SANITIZE_STRING()过滤掉危险的文字输入

echo filter_var ($text_text, FILTER_SANITIZE_STRING); 

请参阅所有可用的消毒方法清单sanitization: https://www.php.net/manual/en/filter.filters.sanitize.php

更新

还有一件事。即使使用pdo,您仍然可能容易受到sql注入攻击。这是因为pdo通过模拟已弃用的mysql_real_escape_string()函数来执行清理操作。您将需要强制pdo禁用仿真并使用直接准备的语句。我将更新我的答案

要解决此问题,请参见下面的数据库连接代码。字符集设置为utf8

$db = new PDO ('mysql:host=localhost;dbname=mydb;charset=utf8', 
    'root', // username
        'root123' // password
);

//Disable Emulates pdo and thus forces PDO to use real prepared statement.
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

借助以上内容,您可以100%安全地抵抗各种SQL注入攻击。如果您对此表示赞赏,请给我留言

© www.soinside.com 2019 - 2024. All rights reserved.