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