我有 3 个变量来跟踪在网站上花费的时间
$_SESSION['checkin']; //logged when user first enters the site
$_SESSION['loggedAt']; //logged when the user leaves the site
$_SESSION['timespent']; //time spent in minutes
我想做的是每次用户离开页面时,这些值都会被推送到数据库中。我所做的是使用onbeforeunload。
下面是我如何使用它:
在每一页上:
<script type="text/javascript" src="js/storeSession.js"></script>
storeSession.js:
window.onbeforeunload = confirmExit();
function confirmExit()
{
var xhr = new XMLHttpRequest();
xhr.open('post','../php/storeSession.php',true);
xhr.send();
return "Are you sure you want to leave?";
}
和 storeSession.php:
$_SESSION['loggedAt'] = time();
$temptime = (double)$_SESSION['timespent']/60;
$_SESSION['timespent'] = $_SESSION['loggedAt'] - $_SESSION['checkin'];
mysql_select_db($db, $conn) or die(mysql_error());
$data = mysql_query("INSERT INTO user (user_id, timespent) VALUES ($tempuser, $temptime) ON DUPLICATE KEY UPDATE timespent = timespent + $temptime")
or die(mysql_error());
$_SESSION['timespent'] = null;
$_SESSION['loggedAt'] = null;
$_SESSION['checkin'] = null;
mysql_close($con);
我找不到问题,一切似乎都正常(没有错误等)。有人有什么主意吗?