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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)