« VB6 HTML Parser 備忘 | 首頁 | Linux Shell Script: 自動切換路由 »
2005年07月01日
PHP 程式分享: 網頁計數器
雖然網路上已經有數百種不同的計數器程式或計數服務, 如果不想費心去找, 請參考這個吧!
程式目的:
- 一個計數器程式可供多個不同網頁分別計數
- 只限定某個網域或網址才能引用, 避免被盜用替別人計數
- 排除特定來源 IP (如: LAN 或自己所在公網 IP) 的點閱計數, 避免自己人檢閱時虛增計數
程式需求:
- Apache HTTP Server
- GD lib
- 程式所在目錄可讓 HTTP Server 寫入
程式規格:
- 使用文字檔儲存計數資料
- 使用 GD lib 呈現計數器圖形
- 使用方法: <img src="counter.php?page=pagename" width="45" height="15">
- 計數器文字檔結構:
pagename,hits
如: home,3
實際運作結果:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<?php
$counterfile = "counter.txt";
$counter = 1;
$page = $_GET["page"];
$userip = $_SERVER["REMOTE_ADDR"];
$referer = $_SERVER["HTTP_REFERER"];
if ($page > "" && (substr($referer,7,14) == "cha.homeip.net" ||
$referer == "http://www.aypwip.org/webnote/Jamyy")) {
if (file_exists($counterfile)) {
$flag = true;
$counterlist = file($counterfile);
$fs = fopen($counterfile, "w");
for ($i=0; $i<count($counterlist); $i++) {
$counterfields = split(",", $counterlist[$i]);
if ($counterfields[0] == $page) {
$counter = intval($counterfields[1]);
if (substr($userip,0,10) != "192.168.1.") {
$counter++;
}
fwrite($fs, "$page,$counter\n");
$flag = false;
} else {
fwrite($fs, $counterlist[$i]);
}
}
if ($flag) {
fwrite($fs, "$page,1\n");
}
fclose($fs);
} else {
exec("echo \"$page,1\" > $counterfile");
}
$counter = str_repeat("0", 5-strlen($counter)) . $counter;
} else {
$counter = "ERROR";
}
header("Content-type: image/png");
$im = @imagecreate(45, 15);
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 255, 255, 255);
imagestring($im, 4, 2, 0, $counter, $text_color);
imagepng($im);
imagedestroy($im);
?> |
程式說明:
| 行號 | 說明 |
| 08 | 判斷是否輸入參數: page; 限制 Referer 來源網址 / 網域 |
| 09 | 計數器檔案已存在的處理 |
| 11 | 讀入整個檔案, 資料內容變成陣列 |
| 15 | 逐筆比對 counter.txt 裡的 page name 與傳入的 page 值, 比對成功時的處理 |
| 16 | 因為 counter.txt 是以逗號 ( , ) 分隔, 並以逗號切為陣列處理, 它的數值欄位後面會包含換行符號 ( \n ), 因此在此須將該值轉為數值型態才能運算該值 ( ++ ) |
| 17 | 排除不想觸發計數的使用者網段、網址 |
| 21 | 因傳入的 page name 已在 counter.txt 中找到, 將 flag 設為 false 表示不用在第 27 行寫入初始值 |
| 23 | 讀入的資料已包含換行符號 ( \n ), 寫入時不需再加上 " \n " |
| 27 | 若傳入的 page 值不存在於 counter.txt 中, 則 flag 依然為 true, 程式會寫入該 page name 與 counter 初始值 ( 1 ) |
| 31 | 計數器檔案不存在的處理. 這裡的寫法是以 Linux 指令直接產生檔案與內容 |
| 33 | 長度不足五位數的數值, 前面補零 ( 0 ) |
| 39 | 建立 W: 45 x H: 15 大小的圖片 |
| 40~41 | 影像背景、前景顏色, 分別以 R, G, B 十進位 ( 0 ~ 255) 設定 |
| 42 | 填入字串: $im=影像物件, 4=字體大小, 2=起始X軸, 0=起始Y軸, $counter=輸入字串, $text_color=文字顏色 |
進階功能建議:
- 以參數方式重置 (reset) 或刪除 (delete) counter.txt 內的資料
- 以參數方式彈性設定計數器字型、背景顏色
- 加上 cookie 或 session 避免同一使用者短時間內重複載入網頁造成計數虛增
相關網頁:
Posted by Jamyy at 2005年07月01日 16:27
Trackback Pings
TrackBack URL for this entry:
http://cha.homeip.net/cgi-bin/mt/mt-tb.cgi/97