使用包含的文件设置 PHP cookie 时出现问题


Issue setting PHP cookie with included files

我有以下脚本,如果用户一天没有访问该网站,它会创建一个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"); ?>

问题出在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
?>

祝你好运