【问题标题】:How do I protect my code from HTML Injection? [duplicate]如何保护我的代码免受 HTML 注入? [复制]
【发布时间】:2013-04-19 10:55:52
【问题描述】:

这是我的代码,如何防止人们在评论和名称字段中注入 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 -->    

【问题讨论】:

  • strip_tags() php 函数..
  • 除了您询问的 XSS 问题之外,您还使用了an obsolete database API,应该使用modern replacement。您还容易受到SQL injection attacks的影响,现代 API 可以让您更轻松地从 defend 中获得。
  • 我知道它已经过时了,但这只是为了学校作业,不是一个严肃的网站或类似的东西。

标签: php html string code-injection entities


【解决方案1】:

我认为您正在搜索 strip_tags() 函数

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

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

【讨论】:

  • strip_tags 甚至无法提供强大的 XSS 保护。
  • htmlentities 呢? php.net/manual/en/function.htmlentities.php 这样安全吗?
  • htmlentities 不应该在这种情况下使用。 htmlspecialchars 非常相似并且使用正确的功能,但它只涵盖了一些 XSS 攻击向量。对链接问题的接受答案包含更多信息。
  • 我不想被完全保护,这只是为了学校作业,我只需要一个简单的防止注射的例子。
  • 我已经阅读了有关条形标签等的信息,但我不知道该放在哪里?有人可以告诉我我将把函数放在我的代码中的什么地方让它工作吗?
猜你喜欢
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
  • 2018-06-22
  • 2013-02-19
  • 1970-01-01
相关资源
最近更新 更多