<?php
$hitcountFile = 'hitcount.txt';
$lockFile = 'hitcount_lock.txt';
$lockTimeout = 60; // Lock timeout in seconds (e.g., 60 seconds)

// Attempt to acquire a lock
$lockAcquired = false;
$lockHandle = fopen($lockFile, 'a'); // Open lock file for appending

if (flock($lockHandle, LOCK_EX)) { // Acquire an exclusive lock
    $lockAcquired = true;

    // Check if the hit count file exists
    if (file_exists($hitcountFile)) {
        // Read the current hit count from the file
        $hitcount = (int) file_get_contents($hitcountFile);

        // Increment the hit count
        $hitcount++;

        // Update the hit count in the file
        file_put_contents($hitcountFile, $hitcount);
    } else {
        // Create the hit count file if it doesn't exist
        $hitcount = 1;
        file_put_contents($hitcountFile, $hitcount);
    }

    // Release the lock
    flock($lockHandle, LOCK_UN);
} else {
    // Failed to acquire the lock
    // Log an error or handle the situation where the lock could not be acquired
    // You can customize this part based on your requirements
}

// Close the lock file handle
fclose($lockHandle);

// Cleanup old lock files if they exist and have timed out
if (file_exists($lockFile) && (time() - filemtime($lockFile)) > $lockTimeout) {
    unlink($lockFile);
}

// Return the hit count
if (isset($hitcount)) {
    echo $hitcount;
}
?>

