devshort

private self-hosted shortlink service
git clone https://git.clttr.info/devshort.git
Log (Feed) | Files | Refs (Tags) | README | LICENSE

commit 67ae933690cc472f3f6345b85d761ad9c16ce56c
parent 2c67544b38f6ecfe3652c4d550246f24e5aaf9bb
Author: René Wagner <rwagner@rw-net.de>
Date:   Mon, 17 Aug 2020 17:59:44 +0200

another attempt fixing the lose of stats

Diffstat:
Mindex.php | 14++++++++++++--
Mredirect.php | 17+++++++++++++----
2 files changed, 25 insertions(+), 6 deletions(-)

diff --git a/index.php b/index.php @@ -8,8 +8,18 @@ $stats_path = implode(DIRECTORY_SEPARATOR, array(__DIR__, "data", "stats.json")) $stats_content = json_decode(file_get_contents($stats_path), true); // Count the access -$stats_content["index"][date("Y-m-d")] += 1; -file_put_contents($stats_path, json_encode($stats_content, JSON_PRETTY_PRINT), LOCK_EX); +$statsfile = fopen($stats_path, 'c+'); +if (flock($statsfile, LOCK_EX)) +{ + $stats_content = json_decode(fread($statsfile, filesize($stats_path)), true); + $stats_content["index"][date("Y-m-d")] += 1; + + ftruncate($statsfile, 0); + fseek($statsfile, 0); + fwrite($statsfile, json_encode($stats_content, JSON_PRETTY_PRINT)); + flock($statsfile, LOCK_UN); +} +fclose($statsfile); // Generate custom buttons for the footer $links_string = ""; diff --git a/redirect.php b/redirect.php @@ -17,10 +17,19 @@ $stats_path = implode(DIRECTORY_SEPARATOR, array(__DIR__, "data", "stats.json")) // Count the access to the given $name function count_access($name) { global $stats_path; - - $stats_content = json_decode(file_get_contents($stats_path), true); - $stats_content[$name][date("Y-m-d")] += 1; - file_put_contents($stats_path, json_encode($stats_content, JSON_PRETTY_PRINT), LOCK_EX); + + $statsfile = fopen($stats_path, 'c+'); + if (flock($statsfile, LOCK_EX)) + { + $stats_content = json_decode(fread($statsfile, filesize($stats_path)), true); + $stats_content[$name][date("Y-m-d")] += 1; + + ftruncate($statsfile, 0); + fseek($statsfile, 0); + fwrite($statsfile, json_encode($stats_content, JSON_PRETTY_PRINT)); + flock($statsfile, LOCK_UN); + } + fclose($statsfile); } if (array_key_exists($short, $config_content["shortlinks"])) {