How to use cookies in php

Source: Internet
Author: User
This article describes how to use cookies in php, including creating and updating cookies, deleting cookies, and obtaining cookie values. For more information, see

This article describes how to use cookies in php, including creating/updating cookies, deleting cookies, and obtaining cookie values. For more information, see

1. Create/update cookies

The Code is as follows:


SetCookie ($ cookieName, $ value, time () + seconds );

Example: Create a cookie named UserName with a value of zs and an expiration time of 2 weeks.

The Code is as follows:


Setcookie ("UserName", "zs", time () + 2*7*24*3600 );

If no time is set, it is not saved to the cookie file. When the browser is not closed, it can be accessed. When the browser is closed, it cannot be accessed.

Example:

The Code is as follows:


Setcookie ("Age", "18 ");

2. Retrieve the cookie value

The Code is as follows:


$ _ Cookie [$ cookieName];

Example: extract the UserName value and put it in the variable $ uName.

The Code is as follows:


$ UName = $ _ COOKIE ['username'];

When the value is set, it is generally determined whether it is null before the value operation. The preceding values are generally written as follows:

The Code is as follows:


If (! Empty ($ _ COOKIE ['username'])
{

$ UName = $ _ COOKIE ['username'];

}

3. Delete the specified cookie

The Code is as follows:


Setcookie ($ cookieName, value, time ()-seconds );
// Or
Setcookie ($ cookiename ,'');
// Or
Setcookie ($ cookiename, NULL );


Example: delete UserName

The Code is as follows:


Setcookie ("UserName", "zs", time ()-3600 );

4. Delete all cookies of the current session

The Code is as follows:


Foreach ($ _ COOKIE as $ key => $ val ){
Setcookie ($ key, "", time ()-100 );
}

When no cookie exists, the files that save the cookie on the local machine will also be deleted.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.