如何保护我的代码免受HTML注入?

时间:2013-04-19 10:55:53

标签: php html string code-injection entities

这是我的代码,如何阻止人们在评论和名称字段中注入HTML或类似内容?我读了一些关于html实体和剥离标签的内容,但我不知道如何做到这一点:(

    <?php
error_reporting (E_ALL ^ E_NOTICE); 
require('connect.php');
$name=$_POST['name'];
$comment=$_POST['comment'];
$submit=$_POST['submit'];
if($submit)
{
   if($name&&$comment)
   {
   $query=mysql_query("INSERT INTO comment (id,name,comment) VALUES ('','$name','$comment')");
   header("Location: success.php");
   }
   else
   {
       echo "Please fill out all the fields.";
   }
}
?>
<html>
<head>
 <title>Family Travels - Lanzarote</title>
       <link rel="stylesheet" href="layout2.css" title="style1" media="screen" />   
</head>

<body>

<div id="title">

 <img src="images/banner.png" alt="Title">

</div> <!-- title -->
<div id="container">

<div id="content">
<h2>Share your experience:</h2>

<form action="comment.php" method="POST">
<label>Name:  </label><br /><input type="text" name="name" value="<?php echo "$name" ?>" /><br /><br />
<label>Comment:  </label><br /><textarea style="width:350px;height:130px" name="comment" cols="25" rows="7"></textarea><br /><br /><br />
<input type="submit" name="submit" value="Comment" /><br />
<div style="height:600px;width:500px;overflow:auto;white-space:pre-line;word-wrap:break-word;">
</form>
<hr width="500px" size="3px" />

<?php
require('connect.php');
$query=mysql_query("SELECT * FROM comment ORDER BY id DESC");
 while($rows=mysql_fetch_assoc($query))
    {
    $id=$rows['id'];
    $dname=$rows['name'];
    $dcomment=$rows['comment'];
    $linkdel="<a href=\"delete.php?id=" . $rows['id'] . "\">Delete Comment</a>";
    echo '<font color="white">Name:</font>  ' . $dname . '<br />' . '<br />' . '<font color="white">Comment:</font>  ' . '<br />' . '<br />' . $dcomment . '<br />' . '<br />' . $linkdel . '<br />' . '<br />' . 
    '<hr size="3px" width="500px" />' ;  

   }
?>  
</div>
 </div> <!-- content -->    

1 个答案:

答案 0 :(得分:-1)

我认为您正在搜索strip_tags()功能

http://php.net/manual/en/function.strip-tags.php

它将从字符串中删除所有html和php标记