Umm, actually not the usual ‘Cookie’ that we eat!
Those of you who have created the Polling System that we discussed in Creating a Simple Polling System in PHP, know that the system was simple enough to let the same user vote over and over gain multiple times. It is an open invitation to spammers and other peoples to manipulate the poll. The real-world polling systems do not let people do that. So, unless we implement some method to fight that, out Polling System can not be used on websites. So, you’ve got to read along if you are interested in creating a ‘real’ polling system. One more thing, it’s not just polling system that requires knowing a unique visitor, there are plenty more applications of it.
We have previously discussed in What is Session Control/Variables? that Session Control helps us know whether consecutive requests are made by the same user or not thus it can be used in polling system to not let the ‘same’ user vote again. But, as we know sessions (by default) last only till browser is closed so, mere restarting of the browser would let the user poll again. While there are ways to make sessions last longer but the use of ‘Cookies’ will be better, also since sessions too use cookie internally.
A Cookie is a piece of information stored on clients’ computer. Its use here is pretty obvious. Whenever someone votes, we’d store a cookie on their PC and next time they try to vote, the cookie will be checked and they’d be shown the ‘Poll Results’ page instead of the poll. Everybody will be checked for the presence of cookie but since new (unique) visitors won’t have it, they’d be allowed to see the poll and vote.
So, how do we store a cookie?
As I said ‘cookie’ is some information stored on the client or visitors’ computer, one thing more, cookies have a lifetime after which they are deleted. So if you set a cookie to last seven days, it wouldn’t be accessible after that. Suppose if your poll is to run for a week, you may set the cookie accordingly so that no one could re-vote within that time. Also if you change the poll after that time, peoples who voted earlier would again be able to vote (as previous cookie would no longer be valid).
We may set cookie using the following PHP function:
bool setcookie(string name[, string value, int expire, string path, string domain, int secure]);
You don’t need to worry about all the parameters as only ‘name’ is required to invoke this function all others are optional. For our purpose though we need to set ‘name’, ‘value’ and ‘expire’. These have their respective meaning, ‘expire’ is the time when after which it’ll expire. ‘expire’ should be in UNIX timestamp, which can easily be created using the mktime() function. ‘mktime’ function has the following form, when we don’t supply values for any or all the parameters, current value is used.
int mktime(int hour, int minute, int second, int month, int day, int year);
You may access the stored cookie using the super-global variable $_COOKIE[]
.
Enough discussion, let’s move on to the coding part, which is below:
<?php
/*
Script: Polling System with Cookies
Date: 3-Jun-08
Copyright 2008 Arvind Gupta
http://learning-computer-programming.blogspot.com/
You are free to modify, change, publish or do whatever with this script
as long as this note is intact. Thank You!
*/
<html>
<head>
<title>Polling System</title>
</head>
<body>
<h1>My Poll</h1>
<?php
//define the POLL edning day and month
//4 and 6 means 4th of June of the current year
define('VOTE_ENDS_DAY',5);
define('VOTE_ENDS_MONTH',6);
//check if cookie is set or not
//if cookie is set, no matter what the
//user is requesting (vote page, vote, results)
//redirect them to the results page
if($_COOKIE['voted']=='yes')
{
//if user is trying to vote again, show a message
if ($_GET['action']=='Vote') echo "<p style=\"color: #ff0000;\">Sorry, but you can only vote once</p>";
//redirect to Results page
$_GET['action']='Results';
}
//connect to MySQL
//provide your 'USERNAME' and 'PASSWORD'
//change 'localhost' to the MySQL server
//host, if MySQL is on a sepearte server
$db=new mysqli('localhost','USERNAME','PASSWORD');
//if this is the first time
//and database is not craeted
if(!$db->select_db('one'))
//create the database
$db->query('create database one');
//select the databasw to work with
$db->select_db('one');
//if table is not created, create it
if(!$db->query('select * from poll'))
{
//create a table for a Poll having three options
$db->query('create table poll (id int auto_increment primary key, option1 int, option2 int, option3 int)');
//create an initail row with value of 0 to each field
$db->query("insert into poll (option1, option2, option3) values (0,0,0)");
}
//someone is trying to vote
if($_GET['action']=='Vote')
{
$option1=$_GET['option1'];
$option2=$_GET['option2'];
$option3=$_GET['option3'];
//--you may add more if needed
//be sure to add same no. of radio buttons
//on the form too.
//if any option was selected, then only save the vote
if($option1!='' || $option2!='' || $option3!='')
{
//fetch initial values of polls in DB
$result=$db->query("select * from poll");
$result=$result->fetch_row();
$op1=$result[1];
$op2=$result[2];
$op3=$result[3];
//increment the voted option
if($option1=='voted') $op1++;
elseif($option2=='voted') $op2++;
elseif($option3=='voted') $op3++;
//save the updated values
$db->query("update poll set option1='$op1', option2='$op2', option3='$op3'");
//calculate vote ending time in UNIX timestamp
$expire=mktime(0,0,0,VOTE_ENDS_MONTH,VOTE_ENDS_DAY);
setcookie('voted','yes',$expire);
//redirect to results page
//by setting the $_GET var
$_GET['action']='Results';
}
}
if($_GET['action']=='Results')
{
//fetch initial values of polls in DB
$result=$db->query("select * from poll");
$result=$result->fetch_row();
$op1=$result[1];
$op2=$result[2];
$op3=$result[3];
//close DB
$db->close();
//using HTML with embedded PHP for ease
?>
<h3>Poll Results</h3>
<p>How does it feel to be able to vote to your own Script?</p>
<p>Very Good!: <?php echo $op1; ?></p>
<p>Not Bad...: <?php echo $op2; ?></p>
<p> Bad...: <?php echo $op3; ?></p>
<?php
//closing of PHP blocks may be done this way
}
else
{//show poll form
?>
<h3>Cast Your Vote</h3>
<form name="form1" id="form1" method="get" action="">
<p>How does it feel to be able to vote to your own Script?</p>
<p>
<input type="radio" name="option1" value="voted" />
Very Good!</p>
<p>
<input type="radio" name="option2" value="voted" />
Not Bad...</p>
<p>
<input type="radio" name="option3" value="voted" />
Bad...</p>
<p>
<input name="action" type="submit" id="action" value="Vote" />
</p>
</form>
<p><a href="?action=Results">Show Results</a></p>
</body>
</html>
<?php
}
?>
Previous Articles: