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

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历