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

PHP 純文字計數器三種寫法:單檔案、系統指令、錯誤處理

     編輯:PHP 相關知識

寫法一:極簡函數 countx()

function countx($file = "count.dat") {
    if(file_exists($file)) {
        $fp = fopen($file, "r");
        $numx = fgets($fp, 10);
        fclose($fp);
        $numx++;
    } else {
        $numx = 1;
    }
    file_put_contents($file, $numx);
    echo $numx;
}
// 呼叫
countx();

寫法二:系統指令操作檔案(不推薦,有注入風險)

$counterfile = "balong.txt";
function displaycounter($counterfile) {
    $fp = fopen($counterfile, "rw");
    $num = fgets($fp, 5);
    $num += 1;
    print "您是第 $num 個看巴泷計數器的家伙";
    exec("rm -rf " . escapeshellarg($counterfile));
    exec("echo $num > " . escapeshellarg($counterfile));
}
if(!file_exists($counterfile)) exec("echo 0 > " . escapeshellarg($counterfile));
displaycounter($counterfile);

寫法三:同上但不同檔名(示範多頁面獨立計數)

$counterfile = "www.bkjia.com.txt";
// 其餘邏輯同寫法二

最佳實踐建議

  • 使用 file_put_contents + file_get_contents 或 fopen + flock 確保並發安全。
  • 避免 exec,若必須用請嚴格 escapeshellarg。
  • 高流量網站建議改用 Redis/Memcached 原子增量,定期持久化至資料庫。
  • 計數器檔案置於公開目錄外,防止被直接下載或竄改。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved