首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 文字計數器極簡實作(檔案儲存版)

     編輯:PHP 綜合知識

核心程式碼

$file = 'count_file.txt';

if (file_exists($file)) {
    $count = (int)file_get_contents($file) + 1;
} else {
    $count = 1;
}

file_put_contents($file, $count);
echo $count;

進階版:支援多頁面獨立計數

function page_counter(string $pageId): int {
    $dir = __DIR__ . '/counters/';
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $file = $dir . md5($pageId) . '.txt';

    $count = file_exists($file) ? (int)file_get_contents($file) : 0;
    $count++;
    file_put_contents($file, $count, LOCK_EX);
    return $count;
}

// 使用
echo '本頁瀏覽次數: ' . page_counter($_SERVER['REQUEST_URI']);

效能與擴展建議

  • 高流量場景請改用 Redis INCR 或 MySQL 原子更新
  • 加入 Cookie/Session 去重,避免刷新重複計數
  • 定期將檔案計數同步至資料庫做持久化分析
  • 使用 LOCK_EX 防止併發寫入資料損壞
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved