How to record page dwell time in PHP_php tips

WBOY
Release: 2016-05-16 19:55:06
Original
1897 people have browsed it

The example in this article describes how PHP records the time spent on a page. Share it with everyone for your reference, the details are as follows:

First add JS to the page you want to monitor 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 = 'log.php&#63;stay_ms=' + ms;
}
</script>

Copy after login

log.php code is as follows

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

Copy after login

Readers who are interested in more PHP-related content can check out the special topics on this site: "Summary of PHP network programming skills", "Introduction to PHP basic syntax tutorial", "Summary of PHP operating office document skills (including word, excel, access, ppt)", "Summary of PHP date and time usage", "PHP object-oriented programming introductory tutorial》, "php string (string) usage summary", "php mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will be helpful to everyone in PHP programming.

Related labels:
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!