Instant Cookie Setting in PHP
To make a set cookie appear immediately
in the $_COOKIE
array, you can
use a clever technique.
The essence of the technique is as follows: first, set
the cookie using setcookie
, and then
manually write it into the $_COOKIE
array:
<?php
setcookie('str', 'eee');
$_COOKIE['str'] = 'eee';
var_dump($_COOKIE['str']); // will immediately output 'eee'
?>
To prevent the cookie from being sent to the browser every time, you can place the cookie setting inside a condition. If the cookie doesn't exist, then set it:
<?php
if (!isset($_COOKIE['str'])) { // if the cookie doesn't exist
setcookie('str', 'eee');
$_COOKIE['str'] = 'eee';
}
echo $_COOKIE['str']; // will output 'eee'
?>
Let's discuss how this works. On the first
visit to the page, we will enter the if
block,
set the cookie in the browser, and immediately write it
into $_COOKIE
. Then, echo
will output the value we manually wrote.
On subsequent visits to the page, we will not enter
the if
block, but $_COOKIE
will contain
our cookie, which has already come from the browser.
Thus, both on the first visit and on
subsequent ones, our cookie will be present
in $_COOKIE
.
Try out the described technique.