dsyak22488 2017-04-12 02:19
浏览 28
已采纳

PHP:为什么我的cookie没有正确设置?

What's wrong with my code? When I run it, it tells me: "Notice: Undefined index: visits" on the lines if($_COOKIE["visits"] == 1) and $numOfVisits = $_COOKIE["visits"]; in the body section.

<!DOCTYPE html>

<?php 
if (!isset($_COOKIE["visits"])) 
    setcookie("visits", 1, time()+3600*24*365);
else{
    $visits = $_COOKIE["visits"] + 1;
    setcookie("visits",$visits, time()+3600*24*365);
}
?>

<html lang="en">
    <head>
        <title>numOfVisits</title>
        <meta charset="utf-8"/>
    </head>
    <body>
        <?php
        if($_COOKIE["visits"] == 1)
            echo("Welcome to my webpage! It is your first time that you are here.");
        else{
            $numOfVisits = $_COOKIE["visits"];
            echo("Hello, this is the #$numOfVisits time that you are visiting my webpage.");
        }
        ?>
    </body>
</html>
  • 写回答

1条回答 默认 最新

  • douzhao9608 2017-04-12 02:28
    关注

    The problem is that you can only set cookies or start sessions before any headers are send from the server to the client. (See documentation on setcookie)

    setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

    What this means in practise is that you can't set a cookie after you already output something. In this case you're outputting <!doctype html> before you are setting the cookie.

    The solution is to set the cookie before you output any HTML.

    So solution:

    <?php 
    if (!isset($_COOKIE["visits"])) 
        setcookie("visits", 1, time()+3600*24*365);
    else{
        $visits = $_COOKIE["visits"] + 1;
        setcookie("visits",$visits, time()+3600*24*365);
    }
    ?>
    <!doctype html>
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!