Reputation: 19
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?
Upvotes: 1
Views: 3296
Reputation: 11
No need for database storage to this. Instead, on vote:
set_cookie($_POST['id'], "1", time()+60*60*24*365)
Then when you display a post check if the cookie is set with:
if(!($_COOKIE[$_POST['id']])){ //if user hasn't voted
// display vote buttons
}else{
// don't display vote buttons
}
Upvotes: 1
Reputation: 1
Another way to ensure that users only vote once, without creating a user account, is to create a voting system where the user has to provide their email address for confirmation.
The above steps can also be used (with minor variations) to confirm age or other important demographic information for the contest. We've used this approach quite a bit in running contests on our clients site and it has worked well.
Upvotes: 0
Reputation:
How about simplified
<?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
}
?>
But in the end, you should use user accounts or cookies. While the user can clear the browser of cookies, the user may also have a dynamic IP address. This would also accommodate for users who are using one large network with a single IP (free Wi-Fi networks, schools, workplaces)
I think that making user accounts is the best idea
<?php
$result = mysql_query("SELECT * FROM votes WHERE username = '$_SESSION[username]' AND id = '$id'");
?>
Upvotes: 1