Creating and reading cookie

Software / Browsers / Cookies

Creating and reading cookie

Required parameters

Setting up cookies through PHP


So we created a variable named Name, with a value of $Vladimir.
Now, wherever we make a request for the Name variable, Vladimir will be displayed.

Displaying the value of the cookie

//Вывод одного значения
echo $_COOKIE["TestCookie"];
//вывод всех значений

Delete cookie

To delete a cookie value is very simple - to write again with a zero value.

setcookie ("name", '');

Or set the time of life, after which the variable itself retires.

All parameters

setcookie (name, value, expiration time, path, domain);

name is the name of the variable;
value - the value of this variable;
expire - the time in seconds since the beginning of the epoch, after which the current cookie becomes unreadable;
path - the path by which the cookie is available;
domain - the domain from which the cookie is available;
secure - If this marker is present, the cookie information is sent only via HTTPS (HTTP using Secure Socket Level SSL), in protected mode. If this marker is not specified, then the information is sent in the usual way.

expire - Life time

The lifetime is an optional parameter, but very important, because if you do not specify it, the variable will survive until the browser is closed.

Cookies will be deleted after an hour (3600 seconds)

setcookie ("Name", "Vladimir", time () +3600);

Cookies will be deleted after a year (60 seconds * 60 minutes * 24 hours * 365 days)

setcookie ("Name", "Vladimir", time () + 60 * 60 * 24 * 365);

Cookies will be deleted after a year at midnight on January 25, 2014 year

setcookie ("Name", "Vladimir", mktime (0,0,0,01,25,2010));


By default, cookies are read on the same second-level domain (for example, on ​​which they are created. Using the domain and path parameters, you can restrict the use of cookies.

("Name""Vladimir"time () + 3600"/dir/""");
The cook "Name" with the value "Vladimir" will extend 1 hour, it can be read only by the sites located in the directory "/dir/" on the domain "".

Check if cookies are enabled

For example, you have created a website that is configured to work with a cookie, and the user has been disabled.
You can do this:
  1. a visitor hits a page that specifies cookie values,
  2. Then a query is made for this value,
  3. If there is no variable, then there is a redirect to a page with text like "you got here because you have cookies disabled." Next is a description of how to enable them and a warning - otherwise some of the functions on this site will be unavailable.

Example of visit counter

"You visited the page " $_COOKIE["counter"] . " times";