龙空技术网

PHP记录用户访问ip、浏览器类型和访问时间到txt日志文件

猿来了 257

前言:

当前你们对“php浏览器信息”可能比较着重,咱们都想要了解一些“php浏览器信息”的相关资讯。那么小编在网上收集了一些有关“php浏览器信息””的相关文章,希望朋友们能喜欢,朋友们一起来了解一下吧!

Log.class.php

<?php

/*

* 日志记录

* 每天生成一个日志文件,当文件超过指定大小则备份日志文件并重新生成新的日志文件

*

*/

class Log {

private $maxsize = 1024000; //最大文件大小1M

//写入日志

public function writeLog($filename,$msg){

$res = array();

$res['msg'] = $msg;

$res['logtime'] = date("Y-m-d H:i:s",time());

//如果日志文件超过了指定大小则备份日志文件

if(file_exists($filename) && (abs(filesize($filename)) > $this->maxsize)){

$newfilename = dirname($filename).'/'.time().'-'.basename($filename);

rename($filename, $newfilename);

}

//如果是新建的日志文件,去掉内容中的第一个字符逗号

if(file_exists($filename) && abs(filesize($filename))>0){

$content = ",".json_encode($res);

}else{

$content = json_encode($res);

}

//往日志文件内容后面追加日志内容

file_put_contents($filename, $content, FILE_APPEND);

}

//读取日志

public function readLog($filename){

if(file_exists($filename)){

$content = file_get_contents($filename);

$json = json_decode('['.$content.']',true);

}else{

$json = '{"msg":"The file does not exist."}';

}

return $json;

}

}

?>

index.php

<?php

ini_set('date.timezone','Asia/Shanghai');

require_once('Log.class.php');

$filename = "logs/log_" . date("Ymd", time()) . ".txt";

$msg = array(

'ip' => $_SERVER["REMOTE_ADDR"],

'user' => getBrowser()

);

$Log = new Log();

$Log->writeLog($filename, $msg);

$loglist = $Log->readLog($filename);

//获取浏览器类型

function getBrowser() {

$user_OSagent = $_SERVER['HTTP_USER_AGENT'];

if (strpos($user_OSagent, "Maxthon") && strpos($user_OSagent, "MSIE")) {

$visitor_browser = "Maxthon(Microsoft IE)";

} elseif (strpos($user_OSagent, "Maxthon 2.0")) {

$visitor_browser = "Maxthon 2.0";

} elseif (strpos($user_OSagent, "Maxthon")) {

$visitor_browser = "Maxthon";

} elseif (strpos($user_OSagent, "Edge")) {

$visitor_browser = "Edge";

} elseif (strpos($user_OSagent, "Trident")) {

$visitor_browser = "IE";

} elseif (strpos($user_OSagent, "MSIE")) {

$visitor_browser = "IE";

} elseif (strpos($user_OSagent, "MSIE")) {

$visitor_browser = "MSIE 较高版本";

} elseif (strpos($user_OSagent, "NetCaptor")) {

$visitor_browser = "NetCaptor";

} elseif (strpos($user_OSagent, "Netscape")) {

$visitor_browser = "Netscape";

} elseif (strpos($user_OSagent, "Chrome")) {

$visitor_browser = "Chrome";

} elseif (strpos($user_OSagent, "Lynx")) {

$visitor_browser = "Lynx";

} elseif (strpos($user_OSagent, "Opera")) {

$visitor_browser = "Opera";

} elseif (strpos($user_OSagent, "MicroMessenger")) {

$visitor_browser = "微信浏览器";

} elseif (strpos($user_OSagent, "Konqueror")) {

$visitor_browser = "Konqueror";

} elseif (strpos($user_OSagent, "Mozilla/5.0")) {

$visitor_browser = "Mozilla";

} elseif (strpos($user_OSagent, "Firefox")) {

$visitor_browser = "Firefox";

} elseif (strpos($user_OSagent, "U")) {

$visitor_browser = "Firefox";

} else {

$visitor_browser = "其它";

}

return $visitor_browser;

}

?>

标签: #php浏览器信息