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

yipeiwu_com6年前PHP代码库

本文实例讲述了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程序设计有所帮助。

相关文章

PHP解耦的三重境界(浅谈服务容器)

阅读本文之前你需要掌握:PHP语法,面向对象 在完成整个软件项目开发的过程中,有时需要多人合作,有时也可以自己独立完成,不管是哪一种,随着代码量上升,写着写着就“失控”了,渐渐“丑陋接口...

解析func_num_args与func_get_args函数的使用

func_num_args函数功能– 返回传递到函数的参数数目,其语法如下 : int func_num_args (void )。说明 : 返回传递到目前定义函数的参数数目。如果是从函...

基于preg_match_all采集后数据处理的一点心得笔记(编码转换和正则匹配)

1、使用curl实现站外采集 具体请参考我上一篇笔记:https://www.jb51.net/article/46432.htm 2、编码转换首先通过查看源代码找到采集的网站使用的编码...

PHP+Ajax简单get验证操作示例

PHP+Ajax简单get验证操作示例

本文实例讲述了PHP+Ajax简单get验证操作。分享给大家供大家参考,具体如下: 1、显示页面代码 index.html <!DOCTYPE html> <htm...

PHP支持多种格式图片上传(支持jpg、png、gif)

此处一次支持上传2个图片,上传后生成原图和质量较差的图,原图用于保存质量高的图片,质量差的图用于网页显示。 PHP Code 复制代码 代码如下: <?php include_on...