dongxu6418 2018-03-22 13:37
浏览 342
已采纳

PHP:if(isset($ _ COOKIE ['name']))无效

I made an input form when the user types in a name. a isset($_COOKIE) checks if the made cookie already exists. if the cookie exists you'll get a message: Welcome back. if not you'll get the message: this is your first time here. but somehow i always get the message welcome back.

Here is my code:

<?php 
 if(!empty($_POST)) 
 {
    header("Location:form_data.php");
    setcookie('name',$_POST['name'], time() + (86400 * 30));
 }
 if(isset($_COOKIE['name']))
 {
   echo "Welcome back ".$_COOKIE['name'];
 }else
 {
    echo "hello ".$_COOKIE['name']; echo " this is your first time here.";
    setcookie('name',$_POST['name'], time() + (86400 * 30));
 }

?>

can someone help me with this problem?

  • 写回答

2条回答 默认 最新

  • duanmeng3573 2018-03-22 13:41
    关注

    setcookie() must be called before any output is sent to the browser. Otherwise it will cause an header error.

    In your code:

    Change from:

     echo "hello ".$_POST['name']; echo " this is your first time here.";
     setcookie('name',$_COOKIE['name'], time() + (86400 * 30));
    

    To:

      setcookie('name',$_POST['name'], time() + (86400 * 30));
      echo "hello ".$_POST['name']; echo " this is your first time here.";
    

    So no other code will be executed after header() redirection, you should append exit() to it:

    So also change:

    header("Location:form_data.php");
    setcookie('name',$_POST['name'], time() + (86400 * 30));
    

    To:

    setcookie('name',$_POST['name'], time() + (86400 * 30));
    header("Location:form_data.php"); exit();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。