开发者

Knowing real time an user is in my site

I have a website, and I have to implement (with PHP and/or JavaScript) an alert message that triggers two minutes after a visitor has entered the site. I've searched, but all solutions I've found are for an unique page. I need the timer counter to start when the user enters my site, no matter through which page. And I need that counter keeps counting while the user navigates my site's pages.

One solution could be using session variables. I can make a script that looks for this variable, if it doesn't exist means that the user is entering the site. Then I set this variable with current time. The script it's in each page, and it will be reading this variable via AJAX each x seconds and I'll know when the user is in my site since two minutes.

I don't know if it's right or not (I've not implemented yet), but I'm not pretty sure if session is the best way. If the user leaves the page but has other navigator windows opened, the session doesn't expire, and if he enters the site again, the counter will not be reset.

So, two questions:

  1. Is there a better method to have more control on the real entering and exiting?
  2. If not, is my above approach开发者_C百科 right?

Thanks.


Something like this should work.

$alert_message = false;

if(!isset($_SESSION['time_entered'])){
    $_SESSION['time_entered'] = time();
}

if($_SESSION['time_entered'] =< time() - 120){
    if(!isset($_SESSION['message_sent'])){
        $alert_message = true;
        $_SESSION['message_sent'] = true;
    }
}

And in <head>:

<?php if($alert_message):?>
<script type="text/javascript">alert("You've been here for at least two minutes.");</script>
<?php endif;?>

Also make sure that you have session_start() at the top of every script.


You don't need AJAX, you just need to store the time in a session variable, and then include some JavaScript on each page, here is an example:

<?php
session_start();

$time = microtime(true);

if (!$_SESSION['foo']) {
    $_SESSION['foo'] = (microtime(true)+120);
}
?>
<script type="text/javascript">
    var timeoutID = setTimeout(function() {
        alert('two minutes have passed');
    }, <?php echo bcsub($_SESSION['foo'], $time)*1000 ?>);
</script>

You will need some additional logic so that it does not keep firing after the 120 seconds are up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜