Portal Message Boards Zones Navigation What's New Resources Members
Check out the Adult NetSurprise Linklist and Submit your site!



ANS Linklist

XRATED BUCKS

BONEFISH

CE CASH 3.0

PUSSY CASH

Main Zone Library Tutorials Resources Message Boards
Tracking Poll Results and Dynamic Display

by TDavid, Script School

The final lesson of the Surfer Interaction course is going to deal with tracking poll results in a simple flat file system and dynamically displaying the results.

Tracking the votes using flat file

In week/lesson #3, we discussed how to receive the vote for our poll and now we are going to write that pollanswer to a file. The process of doing this is fairly straightforward. First we will define our basic file structure

line 0: poll question | poll answer1 separated by pipe | poll answer 2 separated by pipe |
line 1: is option 1 votes
line 2: is option 2 votes

etc.

Since our poll was a simple yes / no poll then the file would look like this:

Do you find this Script School course #6 text useful?|yes|no|
0
0

Let's open a text editor (notepad or wordpad will work fine) and create this file. Make sure you add a new line so the file looks like above.

Next we need to define the place where this file is going to be on the server. It's a good idea to store data files in a non-public area or your data could be viewable from the web like this: 

http://www.scriptschool.com/class/106/results.txt

We need to set the permissions on this file to chmod 666 which is rw-rw-rw. Now we can read and write to this file through our script. Now, as the new votes come in we'll simply increment the numbers in the poll. Now let's work on the code to open the file and increment a vote and view the comments (after //) for each section or line of code:

<?
// absolute directory path, no trailing slash
$path = '/absolute/path/to/non_public_directory';

// load results.txt file contents into array
$pollresults = file("$path/results.txt");

// get number of lines in the results.txt file
$sizepoll = count($pollresults);

// split the first (zero) line for the field descriptions
$splitpoll = explode("|", $pollresults[0]);

// force poll answer to be an integer, no matter what is typed in
$poll_answer = (int)$_POST['pollanswer'];

// check for valid range of poll
if($poll_answer != 0 and $poll_answer <= $sizepoll) {
  // show the field answer by index (optional)
    $answer = $splitpoll[$poll_answer];
   print("The value of pollanswer is: <b>$answer</b>");

    // increment the poll answer by one
   $pollresults[$poll_answer] = $pollresults[$poll_answer] + 1;
   $pollresults[$poll_answer] .= "\n";
   $writepath = $path . '/results.txt';

    // write the new poll results to the results.txt file
   if($fhandle = fopen($writepath, "w")) {
       for($i=0; $i<$sizepoll; $i++) {
          fputs($fhandle, $pollresults[$i]);
       }
       fclose($fhandle);

    // don't show the form to vote
 
 
$dontshowform = 1;

    } else {
      print("<font color='red'>Could not open <b>$writepath</b></font>");
   }
}
?>

The code above just demonstrates how to write the poll results to a file. What is missing is the logic to display the votes. We want to make some system of not showing the poll form to the person who just voted. We will use cookies, although this by far is not the best way to do this for serious poll results. The reason? Because people can turn cookies off and defeat the poll system and vote again and again. We will discuss in the workshop various other methods of securing poll results, so stop by the workshop for this course to learn more about better ways. However, setting a cookie and creating the logic to block future post votes is pretty easy. It works essentially like this:

1. check for cookie existence (pollanswer) -- if the cookie exists then display the poll results, do not display the poll form.
2. If the cookie doesn't exist then check for the pollanswer coming via $_POST (see code above). If the pollanswer is a valid range value within the results.txt file then update the file by incrementing the answer by 1 and then set a cookie in that user's browser so that when they return to the poll they will see the results and not the poll form question.
3. No cookie and no pollanswer? Then we will just default and show the poll form question.

Working Example #1:
http://www.scriptschool.com/class/106/poll.php

Now let's review how to set a cookie. It's done using the function setcookie(). For our example we are going to just create a session-only cookie, but you could easily set a cookie for 30 days or 300 days if you wanted to prevent votes that far into the future. Again, using cookies as a stuff ballot box deterrent is flawed, but it works as a simple example and many of the early poll systems used this type of system exclusively. The code to set the cookie is as follows:

// now set cookie to block dupe votes
setcookie("pollanswer", $poll_answer);

Keep in mind the following whenever you want to set a cookie: you must always set cookies before you print anything -- including whitespace -- to the browser. Cookie setting is done as part of the header process. You will get a "header already sent" error if you try to set a cookie after you have output something to the browser.

Now let's look at the entire source code for the entire poll.php script we are building. This is the code you will need to modify for this week's to-do assignment:

<?
// initialize dontshowform variable
$dontshowform = 0;

$path = '/absolute/path/to/non_public_directory';
$pollresults = file("$path/results.txt");
$sizepoll = count($pollresults);
$splitpoll = explode("|", $pollresults[0]);

// does cookie exist for poll answer?
if ($_COOKIE['pollanswer']) {
   // time to display poll answers, and not ask/nor process pollanswer
   $dontshowform = 1;
    print("$splitpoll[0]<br>
       $splitpoll[1] - $pollresults[1]<br>
       $splitpoll[2] - $pollresults[2]<br>
    ");
} else {
   if ($_POST['pollanswer']) {
      // Perform other checks to validate the poll answer by the user
      $poll_answer = (int)$_POST['pollanswer'];
      if($poll_answer != 0 and $poll_answer <= $sizepoll) {
          $answer = $splitpoll[$poll_answer];
          $pollresults[$poll_answer] = $pollresults[$poll_answer] + 1;
          $pollresults[$poll_answer] .= "\n";
          $writepath = $path . '/results.txt';
          if($fhandle = fopen($writepath, "w")) {
               for($i=0; $i<$sizepoll; $i++) {
                  fputs($fhandle, $pollresults[$i]);
               }
          fclose($fhandle);
          // now set cookie to block dupe votes
         setcookie("pollanswer", $poll_answer);
         $dontshowform = 1;
         print("You selected: <b>$answer</b>");
        
print("<p><a href=\"poll.php\">Click here to see the poll results</a>");

       } else {
          print("<font color='red'>Could not open <b>$writepath</b><p>
            check that results.txt has amenable permissions set</font>
          ");
       }
   } else {
      print("Error! Your poll answer ($poll_answer) is out of the selected range.<p>");
    }
 
}
}

if($dontshowform != 1) {
   echo($splitpoll[0]);
?>

<form method="POST" action="poll.php">
<input type="radio" value="1" checked name="pollanswer">Yes <br>
<input type="radio" value="2" name="pollanswer">No <input type="submit" value="Vote">
</form>

<?
// end dontshowform
}
?>

 We are ready for to-do assignment #4 which is creating the poll script using the information gleaned from week #3 and week #4. If you need help with this week's course then don't forget the course BBS, the live course workshop and the Script School radio show recap.

TO-DO Assignment #4: Add a working poll to your website which will display poll results for those who have answered the polls or the poll form for those who haven't voted using cookies and registered_globals = off code as discussed in week #3. You must use more than 2 options for your poll (so as not to directly copy the code above).

WEEK 4 discussion and questions - this is where you ask questions about this course material and post your weekly "to-do" assignment.
WEEK 4 Workshop Review Wednesday Aug 7, 2002 5:00 PM Eastern / 2pm Pacific - we will review this course material in a LIVE IRC workshop. You can get here by using the JAVA link above or by using your favorite IRC client and pointing to: irc.webmasterlive.com #netsurprise
Script School Live WEEK 4 Audio Review Friday Aug 9, 2002 5:00 PM Eastern / 2:00PM Pacific
- This is the audio recap for the course material where you can call in and ask Q & A LIVE on the radio
Script School Live CHAT (Java) irc.webmasterlive.com #scriptschool (IRC)

TDavid is co-owner, programmer and webmaster for several sites devoted to programming including his own http://www.tdscripts.com/  He has done custom programming in various programming languages for companies all over the world. Every Friday at 2pm PST you can catch his weekly radio show dedicated to the technical side of webmastering and programming at http://www.scriptschool.com/radio


Warning: require(/home/adultnetsurprise.com/public_html/multiforum/feedback.php) [function.require]: failed to open stream: No such file or directory in /home/adultnetsurprise.com/public_html/zones/learning/surfer_interaction/week4.html on line 365

Fatal error: require() [function.require]: Failed opening required '/home/adultnetsurprise.com/public_html/multiforum/feedback.php' (include_path='.:/usr/local/lib/php') in /home/adultnetsurprise.com/public_html/zones/learning/surfer_interaction/week4.html on line 365