user1829627
user1829627

Reputation: 325

How to set persistent cookie

I am using this PHP code and trying to set cookies as shown below:

 setcookie("_GuestID",$userID,time() + (20 * 365 * 24 * 60 * 60));

I found that cookies expire just after closing the browser. I want to make it persistent for a long time. How I can do?

Upvotes: 8

Views: 24032

Answers (3)

Amitesh Bharti
Amitesh Bharti

Reputation: 15775

Let's understand the cookie bit better...

There are two different types of cookies - session cookies and persistent cookies.

  • If a cookie does not contain an expiration date, it is considered a session cookie. Session cookies are stored in memory and never written to disk. When the browser closes, the cookie is permanently lost from this point on.
  • If the cookie contains an expiration date, it is considered a persistent cookie. On the date specified in the expiration, the cookie will be removed from the disk
$cookie_name = "Name";
$cookie_value = "Amitesh";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

Upvotes: 3

brute_force
brute_force

Reputation: 1171

There is no special way to set persistent cookies. Its the same way you set normal cookies. Cookies with an expiration date are called persistent.

Upvotes: 3

nickhar
nickhar

Reputation: 20913

As has already been noted, check if the cookie is actually being set in your browser (your syntax appears correct).

Cookies will only persist for as long as you have set them. I've always used a year as a round period unless there are specific expiry requirements (which are usually much shorter).

Use the strtotime function to make them easier to read:

setcookie( "cookieName1", $value1, strtotime( '+1 year' ) );
setcookie( "cookieName2", $value2, strtotime( '+30 days' ) );

There are many examples of how to use them on the setcookie manual page which is worth taking the time to read.

Upvotes: 10

Related Questions