Example of how PHP records page dwell time

*文
Release: 2023-03-18 19:24:01
Original
1443 people have browsed it

This article mainly introduces the method of PHP recording page residence time, involving PHP combined with js related operation skills for files and time. Friends in need can refer to it. I hope it will be helpful to everyone.

The details are as follows:

First add JS to the page to be monitored as follows

<script>
var dt1 = new Date();
window.onbeforeunload = function(){
  var dt2 = new Date();
  var ms = dt2.getTime() - dt1.getTime();
  var img = new Image();
  img.src = &#39;log.php?stay_ms=&#39; + ms;
}
</script>
Copy after login

log.php code is as follows

<?php
$refer = &#39;&#39;;
if (isset($_SERVER[&#39;HTTP_REFERER&#39;]))
{
  $refer = $_SERVER[&#39;HTTP_REFERER&#39;];
}
$user_agent = &#39;&#39;;
if (isset($_SERVER[&#39;HTTP_USER_AGENT&#39;]))
{
  $user_agent = $_SERVER[&#39;HTTP_USER_AGENT&#39;];
}
$ip = $_SERVER[&#39;REMOTE_ADDR&#39;];
if (isset($_GET[&#39;stay_ms&#39;]))
{
  $log = &#39;[&#39; . date("Y-m-d H:i:s") . &#39;] &#39; . $ip . &#39; &#39; . $refer . &#39; @ &#39; . number_format($_GET[&#39;stay_ms&#39;]) . "ms\r\n";
  file_put_contents("log/log_" . date("Y-m-d") . ".txt", $log, FILE_APPEND);
}
if ($_SERVER[&#39;QUERY_STRING&#39;] == &#39;&#39; || isset($_GET[&#39;day&#39;]))
{
  $day = isset($_GET[&#39;day&#39;]) ? $_GET[&#39;day&#39;] : date("Y-m-d");
  $file = "log/log_" .$day . ".txt";
  if (file_exists($file))
  {
    $log = file_get_contents($file);
    echo nl2br($log);
  }
}
Copy after login

Related recommendations:

php Detailed explanation and difference between time time and date

PHP time formatting parameters

php timestamp

The above is the detailed content of Example of how PHP records page dwell time. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!