PHP Rating Demo

The basic idea of this rating script is to count the number of votes and the ratings and store them in a text file (a database could also be used).

The first step was to create some images to represent the ratings. The easiest approach was to use ImageMagick to create colorful asterisks.

Next, the javascript was written. There was one minor browser compatibility issue with IE, the margin was not included in the offset. A simple fix was to use PHP to synchronize the left margin in the style tag and to add it in later in the javascript, if it was IE.

Finally, the PHP was written and tested. It is listed below.

rating.php5

$sRatingFile='rating.txt';
if (is_file($sRatingFile))
        $sRating=file_get_contents($sRatingFile);
else
        $sRating="0,0";

$aRating=explode(',',$sRating);

if (isset($_GET['r']))
{
        $r=(int)$_GET['r'];
        if (($r<0)||($r>5)) die('Bad rating');
        else
        {
                $aRating[0]++;
                $aRating[1]+=$r;
                file_put_contents($sRatingFile,implode(',',$aRating));
        }
}
$v=$aRating[0];
if ($aRating[0]!=0)
        $r=(int)($aRating[1]/$aRating[0]);
else
        $r=0;

echo<<<INPUT
<p>
<label>Rating</label>
<input name="iRating" id="iRating" type="image" src="images/$r.rating.png" alt="Rating" onclick="ratingClick(event)" />
$v votes
</p>
<div style="display:none">
<img src="images/$r.rating.png" id="imgRating" />
</div>
INPUT;

In a production environment, some CAPTCHA or other tool should be used to prevent automated submissions.