-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHighscoreHandle.php
More file actions
77 lines (67 loc) · 1.68 KB
/
HighscoreHandle.php
File metadata and controls
77 lines (67 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$score = htmlspecialchars($_POST['score']);
if ((!empty($name))&&(!empty($score))) {
add_table_entry($name,$score);
write_table();
}
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
write_table();
}
function add_table_entry($new_name, $new_score){
// create new object:
$new_obj->name = $new_name;
$new_obj->score = $new_score;
$objArray = get_scores_content();
// convert to JSON object:
if(count($objArray)>0){
$new_entry = ',' . json_encode($new_obj) . ']';
}else{
$new_entry = '[' . json_encode($new_obj) . ']';
}
// write:
if($fp = fopen("./scores.json", "c")){
// go to EOF-1:
fseek($fp, -1, SEEK_END);
if(fwrite($fp, $new_entry)===false){
echo 'error writing';
}
fclose($fp);
} else{
var_dump(error_get_last());
}
}
function cmp($a, $b)
{
if ($a->score == $b->score) {
return 0;
}
return ($a->score < $b->score) ? 1 : -1;
}
function get_scores_content(){
$fileContent = file_get_contents("scores.json");
return json_decode($fileContent, false);
}
function write_table(){
write_table_head();
$objArray = get_scores_content();
usort($objArray, "cmp");
foreach ($objArray as $object){
write_table_entry($object->name, $object->score);
}
write_table_end();
}
function write_table_head(){
// begin table:
echo '<table class="hs-table"><tr><th>name</th><th>score</th></tr>';
}
function write_table_end(){
// end table:
echo '</table>';
}
function write_table_entry($cur_name,$cur_score){
echo '<tr><td>' . $cur_name . '</td><td>' . $cur_score . '</td></tr>';
}
?>