PHP记录页面停留时间的方法_php技巧

来源:转载 发布时间:2018-12-13 15:21:50 阅读量:803

本文实例讲述了PHP记录页面停留时间的方法。分享给大家供大家参考,具体如下:

首先在要监控的页面添加JS如下

1

2

3

4

5

6

7

8

9

<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?stay_ms=' + ms;

}

</script>

log.php 代码如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<?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']) ? $_GET['day'] : date("Y-m-d");

  $file = "log/log_" .$day . ".txt";

  if (file_exists($file))

  {

    $log = file_get_contents($file);

    echo nl2br($log);

  }

}


标签: PHP
分享:
评论:
你还没有登录,请先