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.