aboutsummaryrefslogtreecommitdiff
path: root/counter.php
blob: b8117e4d21a57c9deabe09086e3d7b5d45b0a8ff (plain)
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
<?php
header('Content-Type: application/json');
header('Cache-Control: no-store');

$file = __DIR__ . '/counter.dat';

// 24h cookie to dedupe reloads
$cookieName = 'fun_seen';
$shouldIncrement = !isset($_COOKIE[$cookieName]);

if (!file_exists($file)) file_put_contents($file, '0');

$fp = fopen($file, 'r+');
if (!$fp) { echo json_encode(['count' => 0]); exit; }
flock($fp, LOCK_EX);
$count = (int) trim(stream_get_contents($fp));
if ($shouldIncrement) {
  $count++;
  ftruncate($fp, 0);
  rewind($fp);
  fwrite($fp, (string) $count);
  setcookie($cookieName, '1', time() + 86400, '/', '', true, true);
}
flock($fp, LOCK_UN);
fclose($fp);

echo json_encode(['count' => $count]);