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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同