0

我有以下脚本,如果用户一天没有访问该网站,它会创建一个 cookie 并更新数据库记录中的站点计数器,否则它只会显示当前的访问次数。目前,每次我重新加载索引页面时,cookie 都会显示 NULL,因此表会不断更新。包含此脚本时,如何维护索引页面上的 cookie 值?

if (empty($_COOKIE["visits"])) {
            // increment the counter in the database
            mysql_query("UPDATE visit_counter ".
                     " SET counter = counter + 1 ".
                     " WHERE id = 1");

            /* Query visit_counter table and assign counter
               value to the $visitors variable */
            $QueryResult = mysql_query("SELECT counter ".
                    " FROM visit_counter WHERE id = 1");

            // Place query results into an associative array if there are any
            if (($row = mysql_fetch_assoc($QueryResult)) !== FALSE) {
                $visitors = $row['counter'];
            } else {
                // else if this is the first visitor set variable to 1
                $visitors = 1; 
            }

            // Set cookie value
            setcookie("visits", $visitors, time()+(60*60*24));
        } else {
            $visitors = $_COOKIE["visits"];
        }

cookie 脚本包含在索引文件中,因此以下是索引文件...

<?php include("Includes/cookie.php"); ?>
var_dump($_COOKIE["visits"]);        /* Always returns NULL on this page but
                                        returns the cookies real value if 
                                         run straight from cookie.php script */


    /* Some main page content goes here */


   /* The cookie value is echoed in the footer file that is included by
      creating a statement that says echo "total visitors: ".$visitors; */
   <?php include("Includes/footer.php"); ?>
4

1 回答 1

0

问题在于set_cookie

<?php
// Set cookie value
setcookie("visits", $visitors, time()+(60*60*24));
?>

<?php
// Set cookie value
setcookie("visits", $visitors, time()+(60*60*24),'/'); // Define the cookie path to be used on this domain
?>

祝你好运

于 2013-10-23T12:31:02.573 回答