2011-06-03 91 views
1

我正在製作一個動態網頁,允許用戶發佈他們最喜歡的食譜。在每個食譜下面有一個鏈接,可以讓你對食譜做出評論。如果您發表評論,則評論將被髮布到數據庫中,除非評論中有任何撇號。下面是該addcomment.inc.php頁面的代碼:所謂addcomment.inc.php如何正確處理html表單中的撇號?

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

?> 

不同的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"; 

?> 

如何才能使此代碼正確處理單引號如果輸入到註釋表單中?

回答

5

在你粘上任何東西到MySQL查詢使其通過mysql_real_escape_string()

在你粘上任何東西到HTML,讓它通過用htmlspecialchars()

這樣可以防止SQL注入,JavaScript/HTML注入和野火。

2

你必須使用mysql_real_escape_string()

$comment = mysql_real_escape_string($_POST['comment']); 
1

當你將它傳遞給MySQL時,你必須跳過輸入,以避免用戶可以執行SQL injection並對數據庫執行惡意操作。

例子:

// wrong 
$query = "select title from recipes where recipeid = $recipeid"; 
// correct 
$query = "select title from recipes where recipeid = " . mysql_real_escape_string($recipeid); 

您還可以逃避,當你把它傳遞給瀏覽器(以URL或urlencode()htmlspecialchars(),否則有人可能會插入數據庫中的一些惡意的HTML或JavaScript代碼的輸出,然後用XSS attack攻擊您的其他用戶。

實施例:

// wrong 
echo "<input type=\"hidden\" name=\"recipeid\" value=\"$recipeid\">\n"; 
echo "<a href=\"index.php?content=showrecipe&id=$recipeid\">Return to recipe</a>\n"; 
// correct 
echo "<input type=\"hidden\" name=\"recipeid\" value=\"" . htmlspecialchars($recipeid) . "\">\n"; 
echo "<a href=\"index.php?content=showrecipe&id=" . urlencode($recipeid) . "\">Return to recipe</a>\n";