Poll source code

Home
Movies
Images
Java
PHP
Micro controllers
Fractals
Vector graphics
Projects
Links
Blog
Meta

A PHP poll that uses a file to keep track of votes. The file, whose name is set in $pollName, should initially contain a space separated list of zeros (as many as there are answers) and PHP must have permission to both read and write it. A database based approach is in most cases a better idea than this file based approach and that will be added at a later time.
$question = 'Do you like polls?';
$answers = array('Yes', 'No', 
  'This is a silly poll and I refuse to take part in it');
$pollName = 'poll.dat';

if (!isset($_POST['submit'])) {
  print $question;
  print '<br /><br />';
  echo '<form method=post action='poll.php'>';
  for ($i = 0; $i < sizeof($answers); $i++) { 
    print "<input type=radio name=aid value='";
    print $i;
    print "'>";
    print $answers[$i];
    print '</input><br />';
  }
  echo "<input type=submit name=submit value='Vote!'>";
  echo '</form>';
} else {
  if (!isset($_POST['aid'])) {
    die('Please select one of the available choices');
  }
  $data = file_get_contents($pollName)
          or die('Could not read file!');
  $votes = explode(' ', $data);
  $votes[$_POST['aid']] += 1;
  $sum = 0;
  for ($i = 0; $i < sizeof($answers); $i++) {
    $sum += $votes[$i];
  }
  $sum /= 100.0;
  $outfile = fopen($pollName, "w");
  for ($i = 0; $i < sizeof($answers); $i++) {
    echo $votes[$i]." (".round($votes[$i]/$sum)."%) : ";
    echo $answers[$i]."<br />";
    fwrite($outfile, $votes[$i]." ")
          or die('Could not write to file');
  }
}