How to create a basic rating system
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“DTD/xhtml1-transitional.dtd”>
<html>
<body>
<?php if ( (!isset($_POST[’submit’])) ) { ?>
<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>“ method=”post”>
<table>
<tr>
<td>Your rating:</td>
<td><select name=”rate”>
<option value=”1″>1</option>
<option value=”2″>2</option>
<option value=”3″>3</option>
<option value=”4″>4</option>
<option value=”5″>5</option>
</select></td>
</tr>
<tr><td colspan=”2″ align=”center”>
<input type=”submit” value=”Rate it!” name=”submit”/>
</td></tr>
</table>
</form>
<?php
} else {
$rate = isset ($_POST[‘rate’]) ? $_POST[‘rate’] : 0;
$filename = “ratings”;
$alreadyRated = false;
$totalRates = 0;
$totalPoints = 0;
$ip = getenv(‘REMOTE_ADDR’);
// Read the result file
$oldResults = file(‘results/’.$filename.‘.txt’);
// Summarize total points and rates
foreach ($oldResults as $value) {
$oneRate = explode(‘:’,$value);
// If our IP is in the list then set the falg
if ($ip == $oneRate[0]) $alreadyRated = true;
$totalRates++;
$totalPoints += $oneRate[1];
}
// If our rating is valid then append it to the result file
if ((!$alreadyRated) && ($rate > 0)){
$f = fopen(‘results/’.$filename.“.txt”,“a+”);
fwrite($f,$ip.‘:’.$rate.“\n”);
fclose($f);
$totalRates++;
$totalPoints+=$rate;
}
echo “Actual rating from $totalRates rates is: ”
.substr(($totalPoints/$totalRates),0,3).“<br/>”;
// Display the actual rating
for ($i=0;$i<round(($totalPoints/$totalRates),0);$i++){
echo “<img src=’style/star.png’ />”;
}
} ?>
</body>

