用户在网页上花费的时间

时间:2015-12-05 06:22:19

标签: javascript php time

如何使用ajax调用获取在网站上花费的时间并将数据保存到数据库中。我尝试了类似下面的内容,但它没有按预期工作。

<?php

        $ip=$_SERVER['REMOTE_ADDR'];

        $url=file_get_contents("http://ip-api.com/json/$ip");

        //Convert the json to php associative array 
        $data = json_decode($url, true);


        ?>
        <html>
            <head>
                <title>My website</title>
            </head>
            <body>
                Name: <input type="text" id="name">
                <input type="submit" id="name-submit">
                <div id="name-data"></div>

                <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

            <script type="text/javascript">
                 var startTime = new Date();        
                 alert(startTime);
                 window.onbeforeunload = function(ajaxFunc) 
                 {

            var ajaxFunc = function() {
                var timeSpentMilliseconds = new Date().getTime() - startTime;
                var time = timeSpentMilliseconds / 1000 / 60;

                $.ajax({
                    type: 'GET',
                    url: 'http://example.com/get_time/index.php',
                    data: 'time=' + timeSpentMilliseconds + '&t=' + time
                });
            };

        });
            </script>
            </body>
        </html>

1 个答案:

答案 0 :(得分:1)

快速而肮脏的方法

我们将每隔N秒使用服务器轮询来手动计算用户在网站上花费的时间。为了防止累积错误,我会添加M(M > N)的阈值。

我所做的是建立一个这样的数据库表:

+--------------+------------+-------------+
| ip           | total_time | last_update |
+--------------+------------+-------------+
| 12.214.43.41 | 581        | 1456534430  |
+--------------+------------+-------------+
| 41.61.13.74  | 105        | 1456538910  |
+--------------+------------+-------------+
| 112.31.14.11 | 4105       | 1456241333  |
+--------------+------------+-------------+

然后,您有一个服务器端脚本执行下一个:

server.php

<?php
$servername = 'localhost';
$dbname     = 'cooldb';
$username   = 'dbuser';
$password   = 'changeit';
$table      = 'timers';
// Session timeout - threshold that user have left the site.
$session_timeout = 60;
$ip              = $_GET['REMOTE_ADDR'];
$now             = time();
$total_time      = 0;
$last_update     = time();
try {
    $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // Set the PDO error mode to exception
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // Check if we have ip on our table
    $stmt = $db->prepare("SELECT * FROM {$table} WHERE ip=?");
    $stmt->execute([$ip]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (!empty($rows)) {
        $client      = reset($rows);
        $total_time  = $client['total_time'];
        $last_update = $client['last_update'];
        // Updating $total_time only when user is logged in and sending requests in $session_timeout timespan.
        if ($last_update + $session_timeout > $now) {
            $total_time += $now - $last_update;
        }
        $last_update = $now;
        // Client is already recorded - update the timers.
        $stmt = $db->prepare("UPDATE {$table} SET total_time=?, last_update=? WHERE ip=?");
        $stmt->execute([$ip, $total_time, $last_update]);
    } else {
        // Client have logged in first time - create a record in db.
        $stmt = $db->prepare("INSERT INTO {$table} (`ip`, `total_time`, `last_update`) VALUES ('?', '?', '?')");
        $stmt->execute([$ip, $total_time, $last_update]);
    }
} catch (PDOException $e) {
    echo $e->getMessage();
}
$db = null;

然后,在客户端,您只是发出这样的请求来记录用户活动:

// Something reasonable, below $session_timeout threshold.
var repeat = 20000;
setInterval(function(){ $.get('/server.php', function(){}); }, repeat);

我自己还没有测试过,但我希望你能得到这个想法。