dongra1984 2018-09-06 07:35
浏览 49
已采纳

在使用php在htaccess中重写url后,无法在页面加载时从cookie中检索数组

Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteBase /roots_web/

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteRule ^contact-us.html/$ contact-us.php
RewriteRule ^contact-us.html$ contact-us.php

I'm setting the cookie with:

 setcookie("reports_cookie[".$report_id."][report]", $report_id);

and when I go to other page and check

if(isset($_COOKIE['reports_cookie']) && count($_COOKIE['reports_cookie'])>0)
{
}

it is not evaluating this condition as true.

  • 写回答

1条回答 默认 最新

  • dongzi0857 2018-09-06 07:59
    关注

    Make sure

    setcookie("reports_cookie[".$report_id."][report]", $report_id, time()+3600,"/");
    

    is used BEFORE any output is done to the browser.

    for example

    <html>
     <head>
        <title>
          hello world
        </title>
     </head>
     <?php
       setcookie("reports_cookie[".$report_id."][report]", $report_id, time()+3600,"/");
     ?>
    </html>
    

    will make it fail because the html output will be sent before the cookie header.

    Cookies are set and read by so called header fields. These need to be sent before any output.

    Even a space before the opening php tag can make it fail. even if that space in a file you're "including" before calling the setcookie function.

     <?php setcookie("reports_cookie[".$report_id."][report]", $report_id, time()+3600,"/");
    ^-- a space making your cookies fail
    

    If you don't see a space, you might have a UTF8 BOM field at the start of your php document. Recommended is to set your text editor to another text encoding like ANSI to be able to edit UTF8 BOM so you can remove it and then save it and revert back to UTF8 without BOM.

    Also, make sure you set your cookie on your entire domain. If you fail to specify that then the cookie can only be read on the page that it was set by.

    Also remember to set an expiry time, in this case I set a time of 5 minutes after which the cookie will expire.

     setcookie("reports_cookie[".$report_id."][report]", $report_id, time()+3600,"/");
    

    Also, please think about why you are storing the report ID as an array key and a value...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥15 在现有系统基础上增加功能