我正在跟踪单个用户在我的网站上的时间长度。为了实现这一点,我记录了用户首次加载页面以及每次点击新页面时的时间戳。
一个简短的总结:
数据库表(time_on_site):
+-------+-----+-----------+----+
| start | end | unique_id | id |
+-------+-----+-----------+----+
start
在创建会话时插入时间戳(仅一次)。end
每次onbeforeunload
触发事件时更新时间戳。
这可以很好地跟踪他们在浏览页面时在网站上的时间,但是当他们离开网站(即浏览器关闭/退出)时,就会出现问题,我不知道如何找到它。基本上,end
记录只是没有用时间戳更新。就像浏览器关闭后没有正确调用 AJAX 函数一样。我async
在 AJAX 调用中设置为 false,但这无济于事。
为什么当用户关闭浏览器时此功能不起作用,但在onbeforeunload
事件触发的所有其他时间都起作用?
编辑
错误只是没有检查else if($_GET['when'] == "end")
.
这是我的代码:
索引.php:
// If the session DOES NOT EXIST, make it and set it to TRUE.
if(!isset($_SESSION['new_visit']))
{
$_SESSION['new_visit'] = true;
}
// If the session is TRUE, make it false.
if($_SESSION['new_visit'] == true)
{
$this->db->store_visit();
$_SESSION['unique_session_id'] = hash("sha512", uniqid("", true) . uniqid("", true) . uniqid("", true));
$_SESSION['new_visit'] = false;
}
在 index.php 的底部:
<script type="text/javascript">
if(window.addEventListener)
{
window.addEventListener("load", function(){log_time("start");}, false);
window.addEventListener("beforeunload", function(){log_time("end"); }, false);
}
function log_time(time)
{
var xmlhttp = "";
var session = "<?php echo $_SESSION['unique_session_id']; ?>";
// IE7+, Firefox, Chrome, Opera, Safari.
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
// IE6, IE5.
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "/application/logtime.php?session=" + session + "&when=" + time, false);
xmlhttp.send();
}
</script>
日志时间.php:
//session_start();
require "database.php";
$db = new Database();
$unique_id = $_GET['session']; //$_SESSION['unique_session_id'];
$time = time();
if($_GET['when'] == "start")
{
if($get_rows = $db->mysqli->query("SELECT 1 FROM time_on_site WHERE unique_id = '$unique_id'"))
{
$rows = $get_rows->num_rows;
}
// If rows were afffected, the unique ID has already been stored so we must UPDATE. This happens each time a page is refreshed.
if($rows >= 1)
{
$db->mysqli->query("UPDATE time_on_site SET end = '$time' WHERE unique_id = '$unique_id'");
}
// Else if the rows affected were 0, we must INSERT a new record. This happens once per session (visit).
else
{
$db->mysqli->query("INSERT INTO time_on_site(start, unique_id) VALUES('$time', '$unique_id')");
}
}