我正在制作一个动态网页,允许人们发布他们最喜欢的食谱。每个食谱下方都有一个链接,您可以通过该链接对食谱发表评论。如果您发表评论,除非评论中有任何撇号,否则评论将发布在数据库中。这是 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";
?>
另一个名为 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";
?>
如果输入到评论表单中,我如何才能使这段代码正确处理单引号?
最佳答案
在将任何内容粘贴到 MySql 查询之前,通过 mysql_real_escape_string() 传递它
在将任何内容粘贴到 HTML 之前,通过 htmlspecialchars() 传递它
通过这种方式,您可以防止 SQL 注入(inject)、JavaScript/HTML 注入(inject)和野火。
关于php - 如何正确处理 html 表单中的撇号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6233507/