1

I'm currently following this tutorial to create a simple vote system.

It works fine except for the validation part where user should only be able to vote once. This tutorial uses IP, which doesn't work for users with dynamic IPs

<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];

if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);

if($count==0)
{
// Update Vote.
$sql = "update Messages set up=up+1 where mes_id='$id'";
mysql_query( $sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$id','$ip')";
mysql_query( $sql_in);
echo "<script>alert('Thanks for the vote');</script>";
}
else
{
echo "<script>alert('You have already voted');</script>";
}

$result=mysql_query("select up from Messages where mes_id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
echo $up_value;

}
?>

Is there a better way to ensure that users only vote once?

4

3 回答 3

1

怎么简化

<?php
 //HERE include DB config and set variables
 $result = mysql_query("SELECT * FROM votes WHERE id = '$id' AND ip = '$ip'");
  $count = mysql_num_rows($result);
 if($count > 0){
  echo "<script>alert('You have already voted');</script>";
 }
 else{
  //Update Sets
 }
?>

但最后,您应该使用用户帐户或 cookie。虽然用户可以清除浏览器中的 cookie,但用户也可能拥有动态 IP 地址。这也适用于使用单一 IP 的大型网络(免费 Wi-Fi 网络、学校、工作场所)的用户

我认为创建用户帐户是最好的主意

<?php
 $result = mysql_query("SELECT * FROM votes WHERE username = '$_SESSION[username]' AND id             = '$id'");
?>
于 2012-04-24T06:21:00.147 回答
1

不需要数据库存储。相反,在投票时:

set_cookie($_POST['id'], "1", time()+60*60*24*365)

然后,当您显示帖子时,请检查 cookie 是否设置为:

if(!($_COOKIE[$_POST['id']])){   //if user hasn't voted
  // display vote buttons
}else{
  // don't display vote buttons
}
于 2015-11-18T22:17:16.217 回答
0

另一种确保用户只投票一次而不创建用户帐户的方法是创建一个投票系统,用户必须提供他们的电子邮件地址以进行确认。

  1. 用户通过输入他们的电子邮件地址进行投票;该地址存储在数据库中。
  2. 当用户提交投票时,然后向该地址发送一封电子邮件,要求确认投票
  3. 当投票被确认时,它是一个合法的投票,并且在未来很容易检查
  4. 在流程结束时从数据库中清除未确认的投票

上述步骤也可用于确认比赛的年龄或其他重要的人口统计信息(略有不同)。在我们的客户网站上举办比赛时,我们已经多次使用这种方法,并且效果很好。

于 2013-05-22T11:26:29.247 回答