PHP 功能強大,只需簡單代碼即可快速建立計數器。核心原理:指定一個記錄檔(如 counter.txt),每次造訪將計數加 1 並顯示。
<?php
$countfile = 'js/counter.inf';
if (($fp = fopen($countfile, 'r+')) === false) {
die("Open file $countfile failed!");
}
$count = (int)fread($fp, 10);
$count++;
fclose($fp);
$fp = fopen($countfile, 'w+');
fwrite($fp, $count);
fclose($fp);
// 文字模式直接輸出
echo $count;
?>
將數字拆解為個位數字,對應顯示預先準備的數字圖片(0.gif ~ 9.gif)。
<?php
$fp = fopen($countfile, 'r');
$counter_array = array();
$array_count = 1;
while (!feof($fp)) {
$digit = fgetc($fp);
if ($digit !== false) {
$counter_array[$array_count] = $digit;
$array_count++;
}
}
fclose($fp);
$array_elements = count($counter_array);
// 輸出 HTML 表格與圖片
echo '<table border="0" height="5" align="center"><tr><td bgcolor="#bab389" align="center">歡迎您,第';
for ($array_id = 1; $array_id < $array_elements; $array_id++) {
echo '<img src="images/counter' . $counter_array[$array_id] . '.gif" align="absmiddle">';
}
echo '位客人</td></tr></table>';
?>
images/counter/ 目錄下,檔名為 0.gif 至 9.gif。