I'm using a simple PHP poll script (http://www.w3schools.com/php/php_ajax_poll.asp) But it doesn't have a way to prevent people from voting multiple times. Is there a way to add a cookie to the script to limit开发者_JAVA百科 users to one vote?
Limiting to cookies isn't probably the best approach to do it, since a person could clear them out and vote unlimited times. On the other hand, if you can use a database, the best approach IMO is to get their IP's and place them on a table, and check when they're trying to vote again.
However, if you still want to do it that way, you can setCookie (http://php.net/manual/en/function.setcookie.php) with the following format:
setCookie("pollCookie", "1", "999999", "/").
Then, when people tries to vote, you can check with
if(isset($_COOKIE["pollCookie"]))
{
echo "You already voted;"
die;
}
Note, again, that this isn't a good way to do it. Moreover, you would have to change the cookie expire date in case they don't clear the cookies.
I don't think there is a perfect answer to your question. I think cookies could limit very few users to only one vote, but very easy to circumvent. I could use a different browser on the same computer, or clear the cookies from my browser. Maybe combined with a sessions variable, or storing the ip-address locally - but these are also not perfect solutions, as you can easily vote from separate ip addressed multiple times. If you require registration, and login with session variables, then at least you could limit one vote per registered user, which in turn could be limited to one per email address - but again not perfect as user could have several email addresses. Personally, when I had to implement a voting system, I allowed people to vote quite openly, then recorded voting patterns (there were multiple categories) and ip addresses and weeded out any obviously dubious votes via a purpose built script. Maybe a combination of the ideas above will suffice for your needs.
you can use cookie for storing a flag value to detect if the user has voted but not, but cookie can be modified and deleted, so a session should be used ! You can use it in your database too !
You can save the cookie and the ip address in a temp db table, that can be flush everyday or if you have user account on your website than you can mark the user as voted.
If you decide to save the ip and cookie, make sure that you check for both to see if one one or the other are present because the user can easily delete the cookie, but it is not an easy thing to change your ip address.
I hope that helps :)
精彩评论