在mysql数据库中安全地保存和显示HTML和特殊字符?

Ty *_*ley 1 php mysqli html-entities htmlspecialchars

标题基本上总结了它.我建了一个小博客,但我甚至无法在我的文章中发布链接!我能做什么?我试过htmlentities(),htmlspecialchars(),real_escape_string()基本上逃避各种形式存在.我使用PHP 5.3和MySQL 5.1

这是我将博客保存到db的代码:

function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlentities($data);
if ($problem && strlen($data) == 0)
{
    die($problem);
}
    return $data;
}

if(isset($_POST['addBlog'])) { //form submitted?

// get form values, escape them and apply the check_input function
$title = $link->real_escape_string($_POST['title']);
$category = $link->real_escape_string(check_input($_POST['category'], "You must choose a category."));
$content = $link->real_escape_string(check_input($_POST['blogContent'], "You can't publish a blog with no blog... dumbass."));
$date = $link->real_escape_string(check_input($_POST['pub_date'], "What day is it foo?"));

 // our sql query
$sql = $link->prepare("INSERT INTO pub_blogs (title, date, category, content) VALUES (?, ?, ?, ?)");
$sql->bind_param('ssss', $title, $date, $category, $content);


//save the blog     
#mysqli_query($link, $sql) or die("Error in Query: " . mysqli_error($link));
$sql->execute();

if (!$sql) 
{
    print "<p> Your Blog Was NOT Saved. </p>";
}
}   
Run Code Online (Sandbox Code Playgroud)

这是我显示博客的代码:

// Grab the data from our people table
        $result = mysqli_query($link, "SELECT * FROM pub_blogs ORDER BY date DESC") or die ("Could not access DB: " . mysqli_error($link));

        while ($row = mysqli_fetch_assoc($result))
        {   
            $id = $link->real_escape_string($row['id']);
            $title = $link->real_escape_string($row['title']);
            $date = $link->real_escape_string($row['date']);
            $category = $link->real_escape_string($row['category']);
            $content = $link->real_escape_string($row['content']);

            $id = stripslashes($id);
            $title = stripslashes($title);
            $date = stripslashes($date);
            $category = stripslashes($category);
            $content = stripslashes($content);

            echo "<div class='blog_entry_container'>";
            echo "<span class='entry_date'><a href='#'>" .$date. "</a> - </span><span class='blog_title'><a class='blogTitleLink' href='blog-view.php?id=" .$id. "'>" .$title. "</a></span>"; 
            echo "<p>" .$content. "</p>";
            echo "</div>";
        }
Run Code Online (Sandbox Code Playgroud)

Jer*_*her 5

编码字符是一件好事,必须确保不要过度编码.

仅编码当时的/需要/编码.在将HTML放入数据库之前不要对HTML进行编码.您可能希望稍后打印出来,或者您可能希望对其进行搜索.使用适当的SQL转义序列(或者,更好的是,使用PDO).

只有当您将内容发送到浏览器时才能转义HTML,然后您需要决定需要什么样的转义.要转换像<&作为字符实体的东西,以便它们正确显示,然后使用正确的转义方法.