Hey guys, thanks for coming, in this tutorial I will show you how to create a basic and simple to use rating system. I hope it helps ya.
The basics
We divide the task into the following steps:- Display a HTML form where a visitor can select a rating.
- Read the existing results
- Check if the actual IP exists among the old results
- Add valid rating to the result list
- Display the actual rating
Displaying the HTML form
This is an easy part. As usually we create a normal HTML form which is displayed during the first call of the script. As the script itself contains the processing part as well we first check if we really need to display the form or process the submitted data. So the first part of the code looks like this:
Your rating: 1 2 3 4 5
Reading the Existing Results
For the next step we need to process the user input. In this step we initialize some variables to store total ratings, total points, and last, but not least, actual rating. This is quite simple:
Quote:
$rate = isset ($_POST['rate']) ? $_POST['rate'] : 0;
$filename = "ratings";
$alreadyRated = false;
$totalRates = 0;
$totalPoints = 0;
$ip = getenv('REMOTE_ADDR');
?>
|
IP Obtaining, locking in ratings.
Afterwards we retrieve the actual user IP. Later we will check if this IP is already saved in the result list. If there is already a result from the actual IP, then we'll ignore the new one. With this solution we can avoid manipulations of our ratings. So, we need to open the result file and read it into an array using the "file" function. Next, we iterate over this array and summarize the ratings until now. Of course we also check the IP, below will be the coding used for such:
Code:
// 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];
}
?>
Now, if the rating seems to be valid then we open the result file again and append a new result entry at the end of the file with the actual user IP. Besides this we update the total rating points we have collected in the previous step.
The Final Stages:
Lastly, what we want to do is only display the actual rating. We can do that with only displaying the value or we can displaying some graphics like stars to make it a bit nicer.
Code:
echo "Actual rating from $totalRates rates is: "
.substr(($totalPoints/$totalRates),0,3)."
";
// Display the actual rating
for ($i=0;$i<round(($totalPoints/$totalRates),0);$i++){
echo "";
}
?>
Thanks for viewing my tutorial, if you liked this one, don't forget to check out my other tutorials including: