使用包含的文件设置PHP cookie

时间:2013-10-23 12:24:33

标签: php cookies

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

1 个答案:

答案 0 :(得分: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
?>
祝你好运