我正在创建一个动态网页,允许人们发布他们最喜欢的食谱.每个食谱下面都有一个链接,允许您对食谱进行评论.如果您发表评论,评论将发布在数据库中,除非评论中有任何撇号.这是addcomment.inc.php页面的代码:
<?php
$con = mysql_connect("localhost", "test", "test") or die('Sorry, could not connect to database server');
mysql_select_db("recipe", $con) or die('Sorry, could not connect to database');
$recipeid = $_GET['id'];
$query = "select title from recipes where recipeid = $recipeid";
$result = mysql_query($query) or die('Could not retrieve file: ' . mysql_error());
echo "<form action=\"index.php\" method=\"post\">\n";
if (mysql_num_rows($result) == 0) {
$title = "Unknown Title";
}
else {
while($row=mysql_fetch_array($result, MYSQL_ASSOC)) {
$title = $row['title'];
}
}
echo "<h2>Enter your comment for the recipe \"$title.\" </h2>";
echo "<textarea rows=\"10\" cols=\"50\" name=\"comment\"></textarea><br>\n";
echo "Submitted by:<input type=\"text\" name=\"poster\"><br>\n";
echo "<input type=\"hidden\" name=\"recipeid\" value=\"$recipeid\">\n";
echo "<input type=\"hidden\" name=\"content\" value=\"addcomment\">\n";
echo "<br><input type=\"submit\" value=\"Submit\">\n";
echo "</form>\n";
?>
Run Code Online (Sandbox Code Playgroud)
一个名为addcomment.inc.php的不同php文件检索信息.这是下面的代码:
<?php
$recipeid = $_POST['recipeid'];
$poster = $_POST['poster'];
$comment = htmlspecialchars($_POST['comment']);
$date = date("Y-m-d");
$con = mysql_connect("localhost", "test", "test") or die('Could not connect to server');
mysql_select_db("recipe", $con) or die('Could not connect to database');
$query = "INSERT INTO comments (recipeid, poster, date, comment) " .
" VALUES ($recipeid, '$poster', '$date', '$comment')";
$result = mysql_query($query) or die('Could not query databse. ' . mysql_error());
if ($result)
echo "<h2>Comment posted</h2>\n";
else
echo "<h2>Sorry, there was a problem posting your comment</h2>\n";
echo "<a href=\"index.php?content=showrecipe&id=$recipeid\">Return to recipe</a>\n";
?>
Run Code Online (Sandbox Code Playgroud)
如果输入注释表单,如何使此代码正确处理单引号?
在将任何内容粘贴到MySql查询之前,将其传递给mysql_real_escape_string()
在将任何内容粘贴到HTML之前,将其传递给htmlspecialchars()
这样就可以防止SQL注入,JavaScript/HTML注入和野火.
| 归档时间: |
|
| 查看次数: |
7028 次 |
| 最近记录: |