Skip to main content

Enhancing the Poll System Using 'Cookies'

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 valueint expirestring pathstring domainint 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 hourint minuteint secondint monthint dayint 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:

Popular posts from this blog

Fix For Toshiba Satellite "RTC Battery is Low" Error (with Pictures)

RTC Battery is Low Error on a Toshiba Satellite laptop "RTC Battery is Low..." An error message flashing while you try to boot your laptop is enough to panic many people. But worry not! "RTC Battery" stands for Real-Time Clock battery which almost all laptops and PCs have on their motherboard to power the clock and sometimes to also keep the CMOS settings from getting erased while the system is switched off.  It is not uncommon for these batteries to last for years before requiring a replacement as the clock consumes very less power. And contrary to what some people tell you - they are not rechargeable or getting charged while your computer or laptop is running. In this article, we'll learn everything about RTC batteries and how to fix the error on your Toshiba Satellite laptop. What is an RTC Battery? RTC or CMOS batteries are small coin-shaped lithium batteries with a 3-volts output. Most laptops use

The Best Way(s) to Comment out PHP/HTML Code

PHP supports various styles of comments. Please check the following example: <?php // Single line comment code (); # Single line Comment code2 (); /* Multi Line comment code(); The code inside doesn't run */ // /* This doesn NOT start a multi-line comment block /* Multi line comment block The following line still ends the multi-line comment block //*/ The " # " comment style, though, is rarely used. Do note, in the example, that anything (even a multi-block comment /* ) after a " // " or " # " is a comment, and /* */ around any single-line comment overrides it. This information will come in handy when we learn about some neat tricks next. Comment out PHP Code Blocks Check the following code <?php //* Toggle line if ( 1 ) {      // } else {      // } //*/ //* Toggle line if ( 2 ) {      // } else {      // } //*/ Now see how easy it is to toggle a part of PHP code by just removing or adding a single " / " from th

Introduction to Operator Overloading in C++

a1 = a2 + a3; The above operation is valid, as you know if a1, a2 and a3 are instances of in-built Data Types . But what if those are, say objects of a Class ; is the operation valid? Yes, it is, if you overload the ‘+’ Operator in the class, to which a1, a2 and a3 belong. Operator overloading is used to give special meaning to the commonly used operators (such as +, -, * etc.) with respect to a class. By overloading operators, we can control or define how an operator should operate on data with respect to a class. Operators are overloaded in C++ by creating operator functions either as a member or a s a Friend Function of a class. Since creating member operator functions are easier, we’ll be using that method in this article. As I said operator functions are declared using the following general form: ret-type operator#(arg-list); and then defining it as a normal member function. Here, ret-type is commonly the name of the class itself as the ope