简体   繁体   中英

Not able to retrieve array from cookie on page load after url rewritting in htaccess using php

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM