$_COOKIE in PHP. How create, use, remove. Code example open

$_COOKIE in PHP. How create, use, remove. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 5.6 +

Sessions and cookies are designed to store information about users when navigating between multiple pages. When using sessions, data is stored in temporary files on the server. Cookie files are stored on the user’s computer and are sent by the browser to the server upon request.

The setcookie() function is used to set cookies on the user’s computer. It must be called before a response is sent to the user. This function has the following definition:

setcookie(string $name, string $value, int $expire, 
    string $path, string $domain, bool $secure, bool $httponly);

name: the name of the cookie,
value: the value or content of the cookie
expire (optional): expiration time in seconds,
path (optional): path to a directory on the server for which cookies will be available,
domain (optional): specifies the domain for which cookies will be available,
secure (optional): indicates that the cookie value should be transmitted over HTTPS,
httponly (optional): if set to true, cookies will only be accessible via the http protocol.

Create simple cookies

setcookie('login', 'root');
setcookie('password', '12345678');

You can refer to a variable to handle this data $_COOKIE

echo $_COOKIE['login'];

Clear cookies

setcookie("password", "", time() - 3600);
! You must specify all parameters as when creating.

Save arrays in a cookie

setcookie("lang[1]", "PHP");
setcookie("lang[2]", "C#");
setcookie("lang[3]", "Java");

Display cookies on the page

if (isset($_COOKIE["lang"])) {
    foreach ($_COOKIE["lang"] as $name => $value) {
        $name = htmlspecialchars($name);
        $value = htmlspecialchars($value);
        echo "$name. $value <br />";
    }
}
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation