Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setcookie php very slow or what happened?

This is a small test. I set a cookie and then try to access it:

<?php 
setcookie("t",0,time()+900);    
echo ($_COOKIE['t']+10);
setcookie("t",0,time()-3600);   
?>

When I run the code I get an error message as below:

Notice: Undefined index: t in /var/www/x/testcookie.php on line 5
10

Why can't I access the cookie?

like image 674
Tiến Mạnh Avatar asked Dec 02 '25 01:12

Tiến Mạnh


1 Answers

It doesn't work that way. setcookie just says "with next http connection tell client (browser) to set this cookie. The browser sends it back in next http connection, if it has not expired yet. Only then it is contained in $_COOKIE array. So you can check that it is set in PHP after next page reload.

Besides in your code second cookie will not be set, because you outputted something to the browser which is forbidden before setcookie function (any header function).

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE

like image 84
n-dru Avatar answered Dec 04 '25 15:12

n-dru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!