Top Ten High Scores
\n");
$count = 0;
foreach ($scores as $index => $data) {
if (++$count > $GLOBALS['LIST_SIZE']) break;
list($score, $foak, $name, $ip, $age) = $data;
$name = htmlentities($name, ENT_QUOTES);
echo("- $name - $score
\n");
}
echo("
\n");
// if new score is being posted
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$level = 0 + $_POST['foak'];
$score = 0 + $_POST['score'];
// remove excess whitespace from the name
// (especially newlines, which would corrupt our file!)
$name = implode(" ", preg_split("/\s+/", $_POST['name']));
// now append the new score to the list
$scores[] = array($score, $level, $name, $_SERVER['REMOTE_ADDR']);
function cmp($op1, $op2)
{
if ($op1 < $op2) {
return -1;
} elseif ($op1 > $op2) {
return 1;
}
return 0; // $op1 == $op2
}
// sort the merged list
function with_high_scores_first($a, $b) {
return -cmp($a[0], $b[0]);
}
usort($scores, "with_high_scores_first");
// and write the list back to the file:
fseek($fp, 0);
$count = 0;
foreach ($scores as $index => $data) {
if (++$count > $GLOBALS['FILE_SIZE']) break;
list($score, $level, $name, $ip, $age) = $data;
fwrite($fp, "$ip $level $score $name\n");
}
}
// unlock and close the file
flock($fp, LOCK_UN);
fclose($fp);
?>