2012-09-27 40 views
1

标题基本概括起来。我建立了一个小博客,但我甚至不能在我的文章中发布链接!我能做什么?我试过htmlentities(),htmlspecialchars(),real_escape_string(),基本上每种逃生方式都有。我使用PHP 5.3和MySQL 5.1安全地保存和显示mysql数据库中的HTML和特殊字符?

这里是我的代码的博客保存到数据库:

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>"; 
} 
} 

,这里是我的代码,以显示博客:

// 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>"; 
     } 
+1

您正在使用mysqli预准备语句,** AND ** real_escape_string,这意味着您基本上双重转义了您在该查询中使用的每个字段。准备好的陈述中占位符的重点在于你所做的** NOT **需要做任何转义。数据库为你做 –

+0

我知道这一点,我想我已经认为安全性越高越好:/ –

+0

除了额外的工作来取消检索数据后额外的转义层外,你什么也得不到。即使是一个可怕的恶意注入数据库的废话数据是完全安全的,如果你可以安全地进入数据库。例如一层逃逸进去,然后它是无害的。 –

回答

4

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

此时只编码what/needs /编码。在将HTML放入数据库之前不要对HTML进行编码。您可能希望稍后打印出来,或者您可能希望对其执行搜索。为SQL使用正确的转义序列(或者,更好的是,使用PDO)。

只有当你将东西发送到浏览器时,你应该转义HTML,然后你需要决定你需要什么类型的转义。要将诸如<&之类的内容转换为字符实体,以便它们能够正确显示,请使用right escape method

+0

我从输入查询中删除了我的'check_input()'函数,现在看起来好像现在所有的东西都打印出来了,除非HTML无法正常工作......任何想法如何才能正常工作? –

+0

** _不能正确工作_ ** - 我们需要比此更多的信息。更新你正在发生的事情,你的期望和错误消息的问题。 –

相关问题