PHP Cookie


by using the setcookie() function to create a cookie, it returns TRUE, otherwise returns FALSE.

grammar:

bool setcookie(string name[, string value[, int expire[, string path[, string domain]]]])
Parameters Description
name cookie name
value Optional, cookie value
expire optional, expiration time, timestamp format
path Optional, the server-side effective path, /said the entire domain name is valid, the default setting for the current page when the cookie path
domain Optional, a valid domain name for this cookie

Example of creating a cookie:

setcookie("username", "Selema", time() + 3600);

In this example, we set a cookie named username, whose value is Selema, and expires in 1 hour. If the time is omitted, the cookie will expire at the end of the session(typically the browser is closed).

The cookie is stored in a specific format on the user's computer.

A more complete example:

setcookie("username", "Selema", time() + 3600, "/", ".developertut.com ");

The example uses the path and domain arguments, which are valid for the /ide of the developertut.com domain name(ie, all stations are valid).


Read the cookie

PHP has a built-in $_COOKIE variable to access the set cookie value.

example:

echo $_COOKIE["username"]; // output Selema

use the isset() function to detect whether the cookie variable has been set:

if (isset($_COOKIE["username"])) {
    echo "Welcome: ". $_COOKIE["username"];
} else {
    echo "Please login";
}

Destroy cookie

You can destroy a cookie by setting the cookie expiration time to a previous point in time:

setcookie("username", "", time() - 3600);

Tip

  1. Due to protocol restrictions, nothing can be output to the browser before the cookie is set
  2. The cookie does not take effect on the current page that is set. To access the set cookie, another page must be accessed before it expires.
  3. Because cookie information is stored on the user's computer, it is possible to spoof the cookie, causing cookie spoofing. It is generally possible to encrypt the cookie value to prevent spoofing. When the cookie is read, decrypt the cookie



Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook