我试图创建一个像使用Facebook的评论系统.我使用php和jquery.我的代码很完美.用户在textarea,comment_1中写入内容并发布.Comment_1直接出现在textarea下面.如果我刷新页面,我可以在开头看到comment_1.如果我尝试发布新评论(comment_2),则comment_2会在comment_1下显示,而comment_1会在comment_2下显示.例如:
在开始时: comment_1
刷新并发布新评论后:comment_1 / comment_2 comment_1 因此,您可以看到,在刷新页面后,它会将comment_2放在comment_1下面,但也会将comment_1放在它们之上(例如将comment_1保留在"内存"中).如果我刷新页面,我会收到comment_2 comment_1,这是我最终想要的,但是如何在不刷新的情况下执行此操作?这是我的代码:
wall.php
<?php
<script>
$(document).ready(function(){
$("#comment_process").click(function(){
if($("#comment_text").val() != ""){
$.post("comments.php?action=post", { comment: $("#comment_text").val() }, function(data) {
$(".comments").html(data);
$("#comment_text").val("");
});
}
});
});
</script>
<div class="comment_container">
<div class="comment_form">
<textarea id="comment_text" ></textarea>
<input type="button" id="comment_process" value="Post"/>
</div>
</div>
<?php include_once("comments.php");?>
<div class="comments"> </div>
?>
Run Code Online (Sandbox Code Playgroud)
这是comments.php
<?php
function getComments(){
$comments = "";
// use desc order by date in order to display comments by date
$sql = mysql_query("SELECT * FROM comments ORDER BY comment_date DESC ") or die (mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = " <div class='each_comment'> There are no comments ...</div> ";
}else{
while ($row= mysql_fetch_assoc($sql)){
$comments .= "<fieldset> Stefanos Says : <div class='each_comment'> <small><em> ".$row['comment_date']." </em></small><br />".$row['comment']."</div></fieldset> </br>";
}
}
return $comments;
}
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query(" INSERT INTO `comments` (comment, comment_date) VALUES ('".$comment."', now()) ");
return true;
}
if((isset($_GET['action'])) && ($_GET['action'] == "post")) {
postComments($_POST['comment']);
}
echo getComments();
?>
Run Code Online (Sandbox Code Playgroud)
这里的问题是你没有清除原始评论.
移动<?php include_once("comments.php");?>到这个div:
<div class="comments"> </div>
这样,当您使用javascript向该块写入注释时,将替换加载页面时加载的原始注释.
mysql扩展的明显问题正确的做法
你应该如何清理SELECT语句的字符串:
$data = mysql_real_escape_string($_POST['some_data']);
$query = mysql_query("SELECT * FROM some_table WHERE some_value = '$data'");
Run Code Online (Sandbox Code Playgroud)
你应该如何清理SELECT语句的整数:
$data = (int) $_POST['some_data'];
$query = mysql_query("SELECT * FROM some_table WHERE some_value = $data");
Run Code Online (Sandbox Code Playgroud)
请注意,整数周围没有引号.
表观漏洞
Mathew在评论中正确地指出,这个品牌的select语句(由ircmaxell演示)不能正确防止SQL注入攻击:
$data = mysql_real_escape_string($_POST['some_data']);
$query = mysql_query("SELECT * FROM some_table WHERE some_value = $data");
Run Code Online (Sandbox Code Playgroud)
然而,这不是一个漏洞,而是滥用函数,不引用$data我们建议我们搜索整数,但我们已经清理了输入,就像它是一个字符串一样.
如果它是一个整数字段,我们应该将输入值转换为整数.如果它是一个字符串字段,则查询中应该有引号.这里显示的所有内容都是错误地使用了某个功能.
由于您的SELECT声明不接受任何用户输入并只选择所有注释,因此无论如何都没有机会进行此类注入.