• 技术文章 >后端开发 >php教程

    php实现统计网站在线人数的方法_PHP

    2016-06-01 14:35:27原创300
    本文实例讲述了php实现统计网站在线人数的方法。分享给大家供大家参考。具体实现方法如下:

    <?php
    function getIpAddress() { // 取得当前用户的IP地址
     if (getenv('HTTP_CLIENT_IP')) {
     $ip = getenv('HTTP_CLIENT_IP');
     } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
     $ip = getenv('HTTP_X_FORWARDED_FOR');
     } elseif (getenv('REMOTE_ADDR')) {
     $ip = getenv('REMOTE_ADDR');
     } else {
     $ip = $_SERVER['REMOE_ADDR'];
     } 
     return $ip;
    } 
    function writeover($filename,$data,$method = 'w',$chmod = 0){
     $handle = fopen($filename, $method);
     !handle && die("文件打开失败");
     flock($handle, LOCK_EX);
     fwrite($handle, $data);
     flock($handle, LOCK_UN);
     fclose($handle);
     $chmod && @chmod($filename, 0777);
    } 
    function count_online_num($time, $ip) {
     $fileCount = './count.txt';
     $count = 0;
     $gap = 900; //15分钟不刷新页面就
     if (!file_exists($fileCount)) {
     $str = $time . "\t" . $ip . "\r\n";
     writeover($fileCount, $str, 'w', 1);
     $count = 1;
     } else {
     $arr = file($fileCount);
     $flag = 0;
     foreach($arr as $key => $val) {
      $val= trim($val);
      if ($val != "") {
      list($when, $seti) = explode("\t", $val);
      if ($seti ==$ip) {
       $arr[$key] = $time . "\t" . $seti;
       $flag = 1;
      } else {
       $currentTime = time();
       if ($currentTime - $when > 900) {
       unset($arr[$key]);
       }else{
       $arr[$key]=$val;
       }
      } 
      } 
     } 
     if ($flag == 0) {
      array_push($arr, $time . "\t" . $ip);
     } 
     $count = count($arr);
     $str = implode("\r\n", $arr);
     $str.="\r\n";
     writeover($fileCount, $str, 'w', 0);
     unset($arr);
     } 
     return $count;
    } 
    $time = time();
    $ip = getIpAddress();
    $online_num = count_online_num($time,$ip);
    echo $online_num;
    ?>

    希望本文所述对大家的php程序设计有所帮助。

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:php 统计 网站 在线人数
    上一篇:PHP CURL 多线程操作代码实例_PHP 下一篇:百度工程师讲PHP函数的实现原理及性能分析(三)_PHP
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【腾讯云】年中优惠,「专享618元」优惠券!• PHP面试之常见基础算法(附代码示例)• PHP header函数分析详解_PHP• php下清空字符串中的HTML标签的代码_PHP• php session处理的定制_PHP• PHP 5.0对象模型深度探索之访问方式_PHP
    1/1

    PHP中文网