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

PHP 計數器實作:文字版與圖形版完整代碼

     編輯:PHP 綜合知識

文字版計數器 counter_simple.php

<?php
$count_num = 0;
$file = "counter.txt";

if (file_exists($file)) {
    $fp = fopen($file, "r");
    $count_num = (int)fgets($fp, 9);
    fclose($fp);
}
$count_num++;

$fp = fopen($file, "w");
fputs($fp, $count_num);
fclose($fp);

echo "<h2 align=center>您好!您是第 <i>$count_num</i> 位訪客!</h2>";
?>

圖形版計數器 counter_graph.php

<?php
header("Content-type: image/gif");

$count_length = 8;          // 顯示位數
$file = "counter.txt";
$str = 0;

if (file_exists($file)) {
    $fp = fopen($file, "r");
    $str = (int)fgets($fp, $count_length + 1);
    fclose($fp);
}
$str++;

$fp = fopen($file, "w");
fputs($fp, $str);
fclose($fp);

// 前面補零
$str_0 = $str;
$len_old = strlen($str);
for ($i = $len_old + 1; $i <= $count_length; $i++) {
    $str_0 = "0" . $str_0;
}

$font = 3;
$im = imagecreate($count_length * 11 - 1, 16);
$black = ImageColorAllocate($im, 0, 0, 0);
$white = ImageColorAllocate($im, 255, 255, 255);

imagefill($im, 0, 0, $black); // 黑底

ImageString($im, $font, 1, 0, $str_0[0], $white);
for ($i = 1; $i <= $count_length - 1; $i++) {
    imageline($im, $i * 11 - 1, 0, $i * 11 - 1, 16, $white); // 分隔線
    ImageString($im, $font, $i * 11 + 1, 0, $str_0[$i], $white);
}

ImageGif($im);
ImageDestroy($im);
?>

使用方式

  1. 文字版:直接在頁面 include "counter_simple.php" 或 <?php require 'counter_simple.php'; ?>。
  2. 圖形版:在 HTML 中用 <img src="counter_graph.php" /> 引用。
  3. 需確保 counter.txt 可寫入(權限 666 或目錄可寫)。

注意事項

  • 簡易計數器未處理並發競爭,高流量站點建議使用資料庫或 Redis 原子操作。
  • 圖形版需 GD 擴展支援。
  • 可擴充:記錄 IP 去重、多頁面獨立計數、統計圖表等。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved