2012年7月31日 星期二

PHP 訪客計數器(不使用exec與DB)

因客戶需求所以google一下訪客計數器,結果找到Wilson Peng大大的code。
//---------------------------
// 訪客計數器函數 MyCounter()
// Author: Wilson Peng
//        Copyright (C) 1999
//---------------------------
function MyCounter() {
  $counterFile="/tmp".$GLOBALS["PHP_SELF"];
  if (!file_exists($counterFile)) {
    if (!file_exists(dirname($counterFile))) {
      mkdir(dirname($counterFile), 0700);
    }
    exec("echo 0 > $counterFile");
  }
  $fp = fopen($counterFile,"rw");
  $num = fgets($fp,5);
  $num += 1;
  print "$num";
  echo $counterFile;
  exec("rm -rf $counterFile");
  exec("echo $num > $counterFile");
}

不過遇到兩個問題,一是exec權限不足,一是$GLOBALS["PHP_SELF"]無法取得路徑。
一個一個處理吧:
exec是用來新增與刪除檔案,所以用fwrite跟unlink取代
  exec("rm -rf $counterFile");
  exec("echo $num > $counterFile");
改成
  //刪舊檔
  unlink($counterFile);
  //開新檔存新值
  $fh = fopen($counterFile, "w");
  fwrite($fh, $num);
  fclose($fh);


$GLOBALS["PHP_SELF"]是為了針對不同頁面產生不同檔名的counter文件,
這邊用getenv('REQUEST_URI')配合str_replace()來取得目前網頁的檔名,並加上副檔名。
所以將
$counterFile="/tmp".$GLOBALS["PHP_SELF"];
改成
  //用網頁檔名加.count當計數文件檔名
  $counterFile = "./counter/".str_replace("/harland/NewZealand/", "", getenv('REQUEST_URI')).".counter";


最後整個function調整後的成果,不使用exec與DB的訪客計數器如下:
//---------------------------
// 訪客計數器函數 MyCounter()
// Author: Wilson Peng
// Revise: Harland Chou (2012)
//        Copyright (C) 1999
//---------------------------
function MyCounter() 
{
  //用網頁檔名加.count當計數文件檔名
  $counterFile = "./counter/".str_replace("/harland/NewZealand/", "", getenv('REQUEST_URI')).".counter";

  if (!file_exists($counterFile)) 
  {

    if (!file_exists(dirname($counterFile))) 
    {

      mkdir(dirname($counterFile), 0700);
    }
    
      //開新檔存新值
    $fh = fopen($counterFile, "w");
    fwrite($fh, "0");
    fclose($fh);

  }
  
  $fp = fopen($counterFile,"rw");
  $num = fgets($fp,5);
  $num += 1;
  print "$num";
  //echo $counterFile;

  //刪舊檔
  unlink($counterFile);       //刪原檔
  //開新檔存新值
  $fh = fopen($counterFile, "w");
  fwrite($fh, $num);
  fclose($fh);

}

沒有留言:

張貼留言