Page rating with PHP. A file is used to keep track of votes. The file, whose name is set in $ratingsFile, should initially contain a space separated list of five zeros and PHP must have permission to both read and write it. A version of this rating program is used for in the footer of some of my pages. 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.
<?php
//name of the file used to keep track of the ratings
$ratingsFile = 'rating.foo';
//session is used to prevent multiple votes on reload
session_start();
//prints the current ratings
function printRating($fileName) {
$data = file_get_contents($fileName)
or die('Could not read file!');
$votes = explode(' ', $data);
$sum = 0;
$n = 0;
for ($i = 0; $i < sizeof($votes); $i++) {
$sum += ($i+1)*$votes[$i];
$n += $votes[$i];
}
echo "Current rating ($n votes) : ";
if ($n > 0) {
$rating = $sum / $n;
$rating = round(100.0*$rating)/100.0;
echo "$rating";
} else {
echo "N/A";
}
}
if (!isset($_POST['submit'])) {
$_SESSION['hasVoted'] = 0;
?>
Rate this page:<br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="radio" name="rating" value="1">1
<input type="radio" name="rating" value="2">2
<input type="radio" name="rating" value="3">3
<input type="radio" name="rating" value="4">4
<input type="radio" name="rating" value="5">5
<input type="submit" name="submit" value="Vote">
</form>
<?php
printRating($ratingsFile);
} else {
if (!$_SESSION['hasVoted']) {
$rating=$_POST['rating'];
if (is_numeric($rating)
&& $rating >= 1 && $rating <= 5) {
//read current rating
$data = file_get_contents($ratingsFile)
or die('Could not read file!');
$votes = explode(' ', $data);
//add vote
$votes[$rating-1] += 1;
//write new rating
$file = fopen($ratingsFile, 'w')
or die('Could not write file!');
fwrite($file, implode(' ', $votes))
or die('Could not write to file');
fclose($file);
} else {
die('Non-numeric or out of range rating!');
}
$_SESSION['hasVoted'] = 1;
}
printRating($ratingsFile);
}
?>