One of the simplest and most popular add-ons to a Web site is anonline poll, allowing visitors to vote on hot-button issues. In thisarticle, find out how PHP can be used to build a powerful, good-lookingonline poll for your Web site, and also learn a little bit about its imageand cookie manipulation functions.
The way things are currently set up, a single user can vote for a specific option than once, thereby contravening one of the basic principles of democracy: one citizen, one vote. Not many users would have the patience or inclination to do this; however, it *is* a hole, and should be plugged.
I've decided to make it slightly more difficult for users to vote more than once by setting a cookie on their system, once their vote has been successfully cast. With the addition of a few lines of script, I can now check for the presence or absence of the cookie, and thereby decide whether or not to accept the vote.
Here's the updated "vote.php" script:
<?
// vote.php - record vote
// check to ensure that the form has been submitted
if (!$submit || !$response)
{
// rest of error message code
}
// check the cookie to ensure that user has not voted already
else if ($lastpoll && $lastpoll == $id)
{
?>
<html>
<head>
<basefont face="Arial">
</head>
<body bgcolor="white">
<i>You have already voted once. Come back in a few days for another poll,
or <a href=archive.php>click here</a> to view previous polls</i>
<?
}
// all is well - refresh the cookie (or set a new one) and process the vote
else
{
setCookie("lastpoll", $id, time()+2592000);
// rest of vote processing code
}
?>
Once the user votes, a cookie is set on the client
browser; this cookie contains the name-value pair
lastpoll=$id
Now, on each subsequent vote attempt, the script will
first check for the presence of the cookie and, if it exists, the value of the cookie variable $lastpoll. Only if the cookie is absent (indicating that this is a first-time voter) or the value of $lastpoll is different from the identifier for the current poll question (indicating that the user has voted previously, but in response to a different question) will the vote be accepted.
This is by no means foolproof - any reasonably adept user can delete the cookie from the client's cache and vote more than once - but it does perhaps offer an additional layer of security to the process. The ideal method, of course, is to track voters on the server itself, and deny votes to those who have already voted - and indeed, this is a feasible alternative if a site requires users to register with unique usernames before accessing its online polls.
This article copyright Melonfire 2001. All rights reserved.