AJAX - The Complete Reference

(avery) #1

Chapter 2: Pre-Ajax JavaScript Communications Techniques 17


PART I


votes and the current total can be found in http://ajaxref.com/ch2/totals.txt. A basic
initial version of setrating.php is shown here.

<?php
/* Files to write to */
$theFile = "ratings.txt";
$totalsFile = "totals.txt";

/* pull the user ratings via the query string */
if (isset($_REQUEST['rating']))
$rating = $_REQUEST['rating'];
else
$rating = 0;

if (isset($_REQUEST['transport']))
$transport = $_REQUEST['transport'];
else
$transport = "downgrade";
/* record the IP address and time */
$userIP = $_SERVER['REMOTE_ADDR'];
$currentTime = date("M d y h:i:s A");

/* open the file and get the contents */
$filehandle = fopen($theFile, "r");
if ($filehandle)
{
$data = fread($filehandle, filesize($theFile));
fclose($filehandle);
}
else
die('Failed to read file');
/* open the file and write line to the top of the file */
$filehandle = fopen($theFile, "w+");
if ($filehandle)
{
fwrite($filehandle,"$rating\t $transport\t $userIP @ $currentTime \n");
fwrite($filehandle, $data);
fclose($filehandle);
}
else
die('Failed to write file');
//get the totals
$votes = $total = 0;
$filehandle = fopen($totalsFile, "r+");
if ($filehandle)
{
$line = fgets($filehandle, 4096);
$tokens = explode("\t", $line);
if (count($tokens) > 1)
{
$votes = $tokens[0] + 1;
$total = $tokens[1] + $rating;
}
fclose($filehandle);
Free download pdf