Recommended sites
Web Hosting Reviews

Creating a simple file based polling script

Creating a simple file based polling script

In this tutorial I will show you how to create a simple, file based polling system where you can easy setup new polls. No database is required for this script and you only have to maintain one config file.

Step 1.
To create a polling system we need the following data:

  • The question, and only one for each polling
  • The answers, there can be more answers for one question
  • The result, how many times where the various answers selected

The above mentioned data can be stored either in a database or in simple text files. To make the implementation and installation more easy we will use a simple file method.
How many file we require and how their content should look like? With a good structure we can maintain all of the information in one file. The format is the following:

QUESTION
Answer1:count
Answer2:count
...
AnswerN:count


With a concrete example:

What is your favorite color?
red:0
blue:5
green:2
yellow:1
black:0

Of course at the beginning all counter should be 0.

Step 2.
So the use case of our script will look like this:
  • Read the config file
  • Display the questions
  • Process the answer
  • Write the config file with the new values
  • Display the actual result

As first implementation step let's read the config file which is called polldata.txt. I use the PHP built in function file() which reads entire file into an array. After it we get the first line as it is the question and then go through all of the other lines and add each not empty line to the answers array.

The code is the following:

<?php
function readData(){
    global 
$pollQuestion,$answers;
    
// Read configuration
    
$rawdata = file('polldata.txt');
    
// Get the question for polling
    
$pollQuestion = $rawdata[0];
    
    
// Get number of answers - The foirs row is the question
    
$numberOfAnswers = sizeof($rawdata)-1;
    
$count = 0;
    for (
$i=1; $i <= $numberOfAnswers; $i++){
        
$answerData = explode(':',$rawdata[$i]);
        
// If tha actual row is not empty than add to the answers array
        
if (strlen(trim($answerData[0]))>0){
            
$answers[$count]['text']  = $answerData[0];
            
$answers[$count]['count'] = $answerData[1];
            ++
$count;
        }
    }
}
?>


Step 3.
Now create the opposite function the writeData(). We will recreate the file and put the question in the first line and then in a loop we put all answers with their counter to the file. We separate the answer text from the counter with the ':' character. Of course you can use any other character which is not used in the answer texts. If you change it don't forget to change it in the readData() function as well.

The write code looks like this:

<?php
function writeData(){
    global 
$pollQuestion,$answers;
    
$file = fopen('polldata.txt','w');
    
fwrite($file,$pollQuestion."\r\n",strlen($pollQuestion));
    foreach (
$answers as $value) {
        
$row = $value['text'].':'.$value['count']."\r\n";
        
fwrite($file,$row,strlen($row));
    }
    
fclose($file);
}
?>


Step 4.
Now it's time to make the code working. So make a complete web page.
First we read the config data and then check whether the form was submitted or not. If not than we display the question and answers. If the visitor selects one and submits the form than the script will call itself and begins with the form processing. In this case we don't show the form. During the form processing we check which answer was selected and increase its counter by one. After we are ready we will write the new data into the config file and then we displays the actual results.

The complete polling script is the following:

<?php

$pollQuestion 
= '';
$answers = '';

function 
readData(){
    global 
$pollQuestion,$answers;
    
// Read configuration
    
$rawdata = file('polldata.txt');
    
// Get the question for polling
    
$pollQuestion = $rawdata[0];
    
    
// Get number of answers - The foirs row is the question
    
$numberOfAnswers = sizeof($rawdata)-1;
    
$count = 0;
    for (
$i=1; $i <= $numberOfAnswers; $i++){
        
$answerData = explode(':',$rawdata[$i]);
        
// If tha actual row is not empty than add to the answers array
        
if (strlen(trim($answerData[0]))>0){
            
$answers[$count]['text']  = $answerData[0];
            
$answers[$count]['count'] = $answerData[1];
            ++
$count;
        }
    }
}

function 
writeData(){
    global 
$pollQuestion,$answers;
    
$file = fopen('polldata.txt','w');
    
fwrite($file,$pollQuestion."\r\n",strlen($pollQuestion));
    foreach (
$answers as $value) {
        
$row = $value['text'].':'.$value['count']."\r\n";
        
fwrite($file,$row,strlen($row));
    }
    
fclose($file);
}

readData();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "DTD/xhtml1-transitional.dtd">
<html>
<body>
<?php 
if (!isset($_POST['submitBtn'])) {       
   echo 
$pollQuestion; 
?>
   <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="poll">
     <table width="300">
<?php
       
foreach ($answers as $value) {
        echo 
'<tr><td><input type="radio" name="polling" value="'
              
.$value['text'].'"/> '.$value['text'].'</td></tr>';
       }
?>
       <tr><td align="center"><br/>
           <input class="text" type="submit" name="submitBtn" value="Vote" />
       </td></tr>
     </table>  
  </form>
<?php    
} else {
      
$count = 0;
       foreach (
$answers as $value) {
        if (
$value['text']  == $_POST['polling']) {
            
$answers[$count]['count'] = ((int)$value['count'])+1;
            (int)
$totalCount++;
        }
        ++
$count;
       }
           
    
writeData();
    echo 
'Thanks for your vote!';
    
    echo 
'   <table width="300">';
    foreach (
$answers as $value) {
        echo 
'<tr><td> '.$value['text'].'</td><td>'.$value['count'].'</td></tr>';
    }
    echo 
'  </table>';
} 
?>
</body>   

Download:
You can get a simple polling script.

Sponsored links