dongliehuan3925 2015-03-14 13:00
浏览 41
已采纳

如何创建安全cookie? 我尝试了所有的东西,但仍然没有工作

I can set a normal cookie, like only set name, value and expires. But I can't set it into secure cookie or httpOnly cookie or both.

Here is my code:

<?php
setcookie("TestCookie", "CookieValue", 0, null, null, true, true);
if(isset($_COOKIE["TestCookie"])){
    echo '$_COOKIE["TestCookie"] = '.$_COOKIE['TestCookie'];
    session_id($_COOKIE["TestCookie"]);
}
else
    echo "Sorry! Cookie TestCookie was not set.";
?>

I have searched in search engine. Try every way. Such as changing a setting in php.ini etc.

It showed no error but it still doesn't work. Please answer on my question.

  • 写回答

1条回答 默认 最新

  • donglusou3335 2015-03-14 13:06
    关注

    The sixth argument of setcookie ensures that the cookie will be only set for HTTPS requests. Set it to false, or be sure to connect via HTTPS.

    Also, note that setcookie won't modify $_COOKIE, since cookies are loaded only once, before the script's execution.

    If you need to get the value from the $_COOKIE variable, you should set it manually:

    setcookie("TestCookie", "CookieValue", 0, null, null, true, true);
    $_COOKIE["TestCookie"] = "CookieValue";
    

    You can also refresh the page, but that could create a redirection loop for people who have disabled cookies in their browsers:

    <?php
    setcookie("TestCookie", "CookieValue", 0, null, null, true, true);
    if(isset($_COOKIE["TestCookie"])){
        echo '$_COOKIE["TestCookie"] = '.$_COOKIE['TestCookie'];
        session_id($_COOKIE["TestCookie"]);
    }
    else{
        header('Refresh: 0');
        exit();
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?