dongzhan5286 2013-03-14 00:41
浏览 20
已采纳

php setcookie没有按预期工作

I am learning PHP now. Any one can take a look at this and see why the cookie is not set and keep showing as empty?

<?php

    if ($_COOKIE["name"]) {
        echo "welcome back" . $_COOKIE['name'];
    }

    else {
        $fname = $_POST["fname"];
        $age = $_POST["age"];
        if ($fname) {
            echo "your name is ".$fname;
            setcookie("name", $fname, time()+6000);
            echo "cookie" . $_COOKIE['name'];
        }

        if ($age) {
            echo "your age is " . $age;
        }
    }

?>

<html>
<body>
<form action="index.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
<a href="info.php">info</a>
</body>
</html>
  • 写回答

2条回答 默认 最新

  • dqnk57224 2013-03-14 00:46
    关注

    Try

    if ($fname) {
            setcookie("name", $fname, time()+6000);
            echo "your name is ".$fname;
            echo "cookie" . $_COOKIE['name'];
        }
    

    Manual

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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