我正在跟踪个人用户在我网站上的时间长度。为了实现这一点,我记录了用户首次加载页面的时间戳以及每次点击新页面时的时间戳。
简要总结:
数据库表(time_on_site):
+-------+-----+-----------+----+
| start | end | unique_id | id |
+-------+-----+-----------+----+
start
中的INSERT时间戳(仅一次)。end
事件被触发时更新onbeforeunload
中的时间戳。这适用于在浏览页面时跟踪他们在网站上的时间,但是当他们离开网站时(即浏览器关闭/退出),出现了问题,我不知道如何找到它。基本上end
记录没有更新时间戳。就像浏览器关闭时AJAX函数没有被正确调用一样。我在AJAX调用中将async
设置为false,但这没有帮助。
为什么当用户关闭浏览器时此功能不起作用,但是onbeforeunload
事件触发后其他所有时间都会起作用?
修改
错误只是没有检查else if($_GET['when'] == "end")
。
这是我的代码:
的index.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>
logtime.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')");
}
}
答案 0 :(得分:1)
if($_GET['when'] == "start")
{
// ...
}
此条件缺少else
分支,因此如果$_GET['when'] != "start"
,则不会发生任何事情。