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
| <?php
// 1 : on récupère les variables
$nomFichier = './rank.js';
$pseudo = $_POST["pseudo"];
$score = $_POST["score"];
// 2 : on ouvre le fichier
$monfichier = fopen($nomFichier, 'w+');
while (!flock($monfichier,LOCK_EX)) {
// tant que le fichier n est pas dispo, on ne fait rien
}
// 3 : on lit et on ecrit dans le fichier
$contents = file_get_contents($nomFichier);
if (false === $contents) {
die('Erreur lors de la lecture du fichier');
}
$json = json_decode($contents);
if (null === $json) {
die('Erreur lors du décodage json: ' . json_last_error_msg());
}
//recherche
$found = false;
foreach ($json as $item) {
if ($item->name === $pseudo) {
$found = true;
break;
}
}
if ($found) {
$player = $item;
if ($player->score < $score) {
$player->score = $score;
}
} else {
$player = array('pseudo' => $pseudo, 'score' => $score);
array_push($json, $player);
}
$encodedString = json_encode($json);
if (false === $encodedString) {
die('Erreur lors de lencodage json: ' . json_last_error_msg());
}
$result = file_put_contents($nomFichier, $encodedString);
if (false === $result) {
die('Erreur lors de lécriture du fichier');
}
// 4 : quand on a fini de l'utiliser, on deverrouille et on ferme le fichier
flock($monfichier,LOCK_UN);
fclose($monfichier);
?> |
Partager