欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

一个简单的 PHP 访问计数器

程序员文章站 2024-04-03 08:16:40
...
  1. // start at the top of the page since we start a session
  2. session_name('mysite_hit_counter');
  3. session_start();
  4. //
  5. $fn = 'hits_counter.txt';
  6. $hits = 0;
  7. // read current hits
  8. if (($hits = file_get_contents($fn)) === false)
  9. {
  10. $hits = 0;
  11. }
  12. // write one more hit
  13. if (!isset($_SESSION['page_visited_already']))
  14. {
  15. if (($fp = @fopen($fn, 'w')) !== false)
  16. {
  17. if (flock($fp, LOCK_EX))
  18. {
  19. $hits++;
  20. fwrite($fp, $hits, strlen($hits));
  21. flock($fp, LOCK_UN);
  22. $_SESSION['page_visited_already'] = 1;
  23. }
  24. fclose($fp);
  25. }
  26. }
  27. ?>
  28. PHP Hit Counter Example Code
  29. Page content...

  30. This page has =$hits;?> hits

  • 复制代码