Examples of how cookies are used in PHP _php

Source: Internet
Author: User
1. Create/Update cookies
Copy CodeThe code is as follows:
Setcookie ($cookieName, $value, time () + number of seconds);

Example: Create a cookie with a name of username and a value of ZS with an expiration time of 2 weeks
Copy the Code code as follows:
Setcookie ("UserName", "Zs", Time () +2*7*24*3600);

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

Example:
Copy the Code code as follows:
Setcookie ("Age", "18");

2. Take the value of the cookie
Copy the Code code as follows:
$_cookie[$cookieName];

Example: Remove the value of the username and place it in the variable $uname
Copy the Code code as follows:
$uName =$_cookie[' UserName '];

When a value is taken, it is generally judged whether it is empty, and then the value operation is taken. The above value operation is generally written like this:
Copy the Code code as follows:
if (!empty ($_cookie[' UserName '))
{

$uName =$_cookie[' UserName '];

}

3. Delete the specified cookie
Copy the Code code as follows:
Setcookie ($cookieName, Value,time ()-seconds);
Or
Setcookie ($cookiename, ");
Or
Setcookie ($cookiename, NULL);


Example: Delete username
Copy the Code code as follows:
Setcookie ("UserName", "Zs", Time ()-3600);

4. Delete all cookies for the current session
Copy the Code code as follows:
foreach ($_cookie as $key = = $val) {
Setcookie ($key, "", Time ()-100);
}

When there is no cookie, the file that saves the cookie is also 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.