Cookie Lifetime in PHP
You already know that cookies must be written using the
function setcookie
:
<?php
setcookie('test', 'abcde');
?>
However, such cookies do not live long - only
until the browser is closed. You can extend the lifetime
of a cookie using the third parameter,
which accepts a point in time in the
timestamp
format. As soon as this moment
arrives - the cookie will automatically be deleted
by the browser.
However, setting a specific cookie expiration time is not very convenient. It would be more convenient to set a cookie, for example, for an hour from the current time, or for a day, or for a year.
Therefore, the third parameter is usually written
like this: current time + N seconds.
The current time in timestamp format can
be obtained using the function time
.
Let's set a cookie for one
hour as an example. Since there are 3600
seconds in an hour,
let's add this number to the current time:
<?php
setcookie('test', 'abcde', time() + 3600);
?>
When setting cookies, seconds are usually written
in this form:
- this is an hour, 60
* 60
- this is a day. And so on.
This is done so that it is obvious to anyone reading your
code for what period of time the cookie is set.
60
* 60
* 24
Let's set a cookie for a day as an example:
<?php
setcookie('test', 'abcde', time() + 60 * 60 * 24);
?>
Set some cookie for a month.
Set some cookie for a year.
Set some cookie for 10
years.