在 php 中关闭网页时如何取消设置会话 [英] how unset session when close the web page in php

查看:57
本文介绍了在 php 中关闭网页时如何取消设置会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过单击 [x](不是 onunload)关闭页面时,如何取消设置 SESSION.我想在打开页面和关闭时插入,但我不想在刷新时插入.

How can I unset the SESSION when I close the page by clicking [x] (not onunload). I want to insert when opening the page and when closing, but I don't want to insert when refreshing.

if (!isset($_SESSION["visits"]))
    $_SESSION["visits"] = 0;
    $_SESSION["visits"] = $_SESSION["visits"] + 1;
if ($_SESSION["visits"] > 1){echo "You hit the refresh button!";}
else{
    mysql_query(
        "INSERT INTO najd_visit( visit_userId, visit_staticId, visit_page,
            visit_enterTime)VALUES ('$userId', '$Sid', '$title', '$date') ");
    echo "This is my site";
    //unset($_SESSION["visits"]);
}

推荐答案

在页面加载和离开前的 JS 事件(onbeforeunload 事件)上对 php 进行 ajax 调用.

Make ajax calls to your php on JS events of page load and right before leave (onbeforeunload event).

最好依赖像 jQuery 这样的 JS 库,因为两个事件侦听器的直接 JS 跨浏览器实现对编码来说非常棘手.

Better rely on a JS library like jQuery, as direct JS cross-browser implementation of both event listeners is quite tricky to code.

更新.感谢@piers 评论,我发现我的解决方案不完整,因为它会计算页面刷新.如果我正确理解任务,目标是计算页面打开和离开,而不是计算刷新事件.

Upd. Thanks to @piers comment I see my solution is not complete as it would count up on page refresh. If I understand the task correctly, the goal is to count page opens and leaves, not counting refresh events.

所以,也许真的没有必要在页面关闭时取消设置会话——让它在服务器超时时自行消失?

So, perhaps, there's no real need to unset the session on page close - let it vanish itself on timeout at server?

您可以使用 session_id 来确定页面/会话对是否唯一.例如,您可以在会话中保留访问过的页面 URL,以检查您是否已经将其计入:

You can use session_id to determine if the page/session pair is unique. For instance, you can keep visited page URLs in session, to check if you already counted that in:

<?php
$uri = $_SERVER['REQUEST_URI'];
if( is_set( $_SESSION['seen']) {
    if( !in_array( $uri, $_SESSION['seen'])){
        countup( $uri);
    } else {
        // already counted that page
    }
} else { // session doesn't have the seen array yet
    countup( $uri);
}

function countup( $uri) {
    $_SESSION['seen'][] = $uri;
    mysql_query( "
        INSERT INTO najd_visit 
        ( visit_userId, visit_staticId, visit_page, visit_enterTime)
        VALUES ('$userId', '$Sid', '$title', '$date')
    ");
    echo "This is my site";
}
?>

这篇关于在 php 中关闭网页时如何取消设置会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆