PHP如何实现一个高效的简单访问计数器?

更新于
2026-09-26 05:50:06
1阅读来源:SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计222个文字,预计阅读时间需要1分钟。

PHP如何实现一个高效的简单访问计数器?

php

// 定义文件名$fn='hits_counter.txt';$hits=0;

// 读取当前点击数if (($hits=file_get_contents($fn))===false) { $hits=0;}

// 增加点击数$hits++;

PHP如何实现一个高效的简单访问计数器?

<? // start at the top of the page since we start a session session_name('mysite_hit_counter'); session_start(); // $fn = 'hits_counter.txt'; $hits = 0; // read current hits if (($hits = file_get_contents($fn)) === false) { $hits = 0; } // write one more hit if (!isset($_SESSION['page_visited_already'])) { if (($fp = @fopen($fn, 'w')) !== false) { if (flock($fp, LOCK_EX)) { $hits++; fwrite($fp, $hits, strlen($hits)); flock($fp, LOCK_UN); $_SESSION['page_visited_already'] = 1; } fclose($fp); } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PHP Hit Counter Example Code</title> </head> <body> <p>Page content...</p> <div class="counter"> <p>This page has <span><?=$hits;?></span> hits</p> </div> </body> </html>

本文共计222个文字,预计阅读时间需要1分钟。

PHP如何实现一个高效的简单访问计数器?

php

// 定义文件名$fn='hits_counter.txt';$hits=0;

// 读取当前点击数if (($hits=file_get_contents($fn))===false) { $hits=0;}

// 增加点击数$hits++;

PHP如何实现一个高效的简单访问计数器?

<? // start at the top of the page since we start a session session_name('mysite_hit_counter'); session_start(); // $fn = 'hits_counter.txt'; $hits = 0; // read current hits if (($hits = file_get_contents($fn)) === false) { $hits = 0; } // write one more hit if (!isset($_SESSION['page_visited_already'])) { if (($fp = @fopen($fn, 'w')) !== false) { if (flock($fp, LOCK_EX)) { $hits++; fwrite($fp, $hits, strlen($hits)); flock($fp, LOCK_UN); $_SESSION['page_visited_already'] = 1; } fclose($fp); } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PHP Hit Counter Example Code</title> </head> <body> <p>Page content...</p> <div class="counter"> <p>This page has <span><?=$hits;?></span> hits</p> </div> </body> </html>