本文详解如何通过记录登录/退出时间戳并累加秒数,精准统计用户在网站的累计停留时长,避免时间格式混淆与sql逻辑错误。
在Web应用中,准确统计用户页面停留时长(Time on Page)是用户行为分析的关键指标。常见误区是直接对日期字符串做算术运算,或误用数据库函数(如 TIMESTAMPDIFF)覆盖原始累计值。正确做法是:将所有时间差统一转换为秒数(integer),在PHP层完成累加,再持久化为总秒数字段。
以下是一个健壮、可复用的实现方案:
public function calculateTimeOnPage()
{
// ✅ 使用预处理语句防止SQL注入(关键!)
$id = (int)$_SESSION['userid']; // 强制类型转换防恶意ID
$stmt = $this->connection->pdo->prepare("SELECT page_start_time, time_on_page FROM users WHERE id = ?");
$stmt->execute([$id]);
$result = $stmt->fetch();
if (!$result) {
throw new Exception("User not found");
}
$logout_time = date('Y-m-d H:i:s');
$session_seconds = strtotime($logout_time) - strtotime($result['page_start_time']);
$total_seconds = $session_seconds + (int)$result['time_on_page'];
// ✅ 直接更新整数秒,语义清晰且高效
$stmt_up = $this->connection->pdo->prepare("UPDATE users SET time_on_page = ? WHERE id = ?");
$stmt_up->execute([$total_seconds, $id]);
// ✅ 可选:格式化输出易读时长(如 "2 hours and 15 minutes")
echo "Total time on page: " . $this->convertSecToTime($total_seconds) . "\n";
}
// ✅ 提取为独立方法,便于复用
private function convertSecToTime($seconds)
{
$seconds = abs((int)$seconds)
;
$interval = new DateInterval('PT' . $seconds . 'S');
$date1 = new DateTime();
$date2 = (clone $date1)->add($interval);
$diff = $date1->diff($date2); // 注意:这里实际是 diff(0) → 更推荐用 DateTime("@$seconds")
// ✅ 更简洁可靠的实现(推荐)
$dt = new DateTime("@$seconds");
return $dt->format('H:i:s'); // 或自定义:小时/分钟/秒组合(见原函数逻辑)
}error_log("User {$id}: start={$result['page_start_time']}, logout={$logout_time}, session_sec={$session_seconds}, total_sec={$total_seconds}");通过以上设计,你将获得一个稳定、安全、易于扩展的用户停留时长统计系统。