【发布时间】:2018-02-21 14:49:21
【问题描述】:
我正在使用 AJAX、PHP 和 MySQL。在以下我的 PHP 代码中:
if(isset($_GET['postTextComment'])){
// The text of the comment
$htpc = htmlspecialchars($_GET['postTextComment'];);
// ID of post, where comment was written on (comes from hidden input field in HTML)
$postid = $_GET['pid'];
// ID of the user written the comment
$myid = getUID();
// CHECK IF COMMENT IS A STRING
if(is_string($htmlpostcomment)){
// CHECK IF POST ID IS A NUMBER
if(is_numeric($postid)){
// CHECK IF POST IS EMPTY
if($htmlpostcomment == "") {
$errors = "Write something! Nyaaa~";
// OR OVER 3K LETTERS
} elseif($htmlpostcomment > 3000) {
$errors = "Too long! Nyaaa~";
} else {
$insertion = $mysql->prepare("INSERT INTO home_posts_comments (uid,pid,html,timestamp) VALUES (?,?,?,?)");
$insertion->bind_param('ssss', $myid, $postid, $htpc, $posted_on);
$insertion->execute();
echo $htpc;
}
} else {
$errors = "NYAAAA!~~~~~";
}
} else {
$errors = "NYAAAA!~~~~~";
}
}
在这里,我正在检查通过 HTML 中的输入字段发送的文本是否为字符串,以及是否帖子的 ID,最终应显示的评论是否为数字。以及关于空输入等的一些其他验证。
现在是我的 AJAX:
$(document).on('click', '[data-action="post-comment"]', function(e) {
// Stored id of the post, where comment should show up lately
var postcomment_where = $(this).data('storeid');
// Value of the comment-input field
var commentLength = $('#posting-comment-data input[data-storeid="'+postcomment_where+'"]').val();
/* (...Some validations...) */
var data = $('#posting-comment-data[data-storeid="'+postcomment_where+'"]').serialize();
$.ajax({
data: data,
type: "get",
url: "/assets/templates/functions/home/post_comment.php",
beforeSend: function(data){
/* (...Show loader...) */
},
success: function(data){
/* (...Hide loader, append post in post section...) */
},
error: function(data){
/* (...Show some error...) */
}
});
}
仅针对前端进行相同的检查,以便为用户获得更多响应。
最后我的 HTML,这是我正在努力解决的问题:
<form id="posting-comment-data" data-storeid="(...ID of post...)" onsubmit="return false;">
<!--- Comment text input field --->
<input type="text" placeholder="Comment this..." name="postTextComment" id="postTextComment" data-storeid="(...ID of post...)">
<!--- Stored ID of the post, where the comment shall show up lately --->
<input type="hidden" name="pid" value="(...ID of post...)" autocomplete="off">
<!--- Submit Button --->
<button type="button" id="post-button-comment-(...ID of post...)" class="cs-button-send" data-storeid="(...ID of post...)" style="display:none;" data-action="post-comment">
Submit comment
</button>
</form>
现在最大的问题是,人们可以打开每个兄弟的开发工具并在隐藏的输入字段中更改帖子的 ID,这样评论就会出现在不同的帖子上。我已经为这个问题苦苦挣扎了一段时间,但我似乎没有找到一个好的解决方案。
数据库中的表包含唯一帖子 ID、用户 ID、文本和时间戳的行。
【问题讨论】:
-
如果您担心人们猜测
id值,请不要使用增量值。我建议改为 GUID。此外,如果您想确保请求仅来自有效位置,请研究 CSRF 令牌。 -
我有点好奇为什么有人会不厌其烦地为某事写评论……而使用它提供的其他东西写评论会更容易形式。你真的对人们这样做有很大的问题吗?另外,对帖子的评论就是对帖子的评论。考虑到互联网的整体影响,相关性是完全不同的野兽。
-
您可以使用 JWT 令牌并将 ID 包含在令牌中。对令牌的任何更改都会使请求无法验证。
-
好的我刚刚了解了token的使用方法,我现在用这个方法试试。
-
@IncredibleHat 已经实现,但无论如何感谢您的建议 :)
标签: php jquery html mysql ajax