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>
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理