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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题