Cookies tutorial

<< Prev
Next >>


Cookies are data, about the user, stored in a text files, on their own PC.

Normally, when a browser requests a webpage, the server sends it, and then the link between the two is interrupted. At a later request from the browser, the server treats it as a new client.
In order for the server to remember visitor data and its preferences (logins, text size, page mode), cookies have been created. Thus, when you return to that site, the web page will be delivered much faster, with the visitor's preferences.
When a user accesses a web page, their name can be stored in this text file (if the web page has cookies implemented).
Cookies are saved as pairs: name - value:

user = Dan Cojocariu

In Europe, according to the EC Privacy Directive, cookie sites must notify visitors about this and ask for their acceptance to continue viewing the web page.
Please note that cookies are not used to personally identify you. However, we may block their use or delete them all from the PC (but the browsing experience on the sites will be damaged).
Cookies can be implemented using javascript, php, asp, jsp and other technologies.

Cookie using javascript

With javascript, a cookie can be created as follows:

document.cookie = "username=Dan Cojocariu";

A cookie is normally deleted when the browser is closed. However, if we want to persist, we can set the expiration date of this as follows:

document.cookie = "username=Dan Cojocariu; expires=Su, 24 Feb 2019 12:00:00 UTC";

You can also set the path to the page where the cookie acts. By default, it belongs to the current page.

document.cookie = ""username=Dan Cojocariu; expires=Su, 24 Feb 2019 12:00:00 UTC; path=/";

With javascript, the cookie can be read as follows:

var x = document.cookie;

document.cookie will return all cookies in one string: cookie1 = value; cookie2 = value;
Deleting a cookie is done by setting the expiration parameter to a previous date as follows:

document.cookie = "username=; expires=Mo, 01 Feb 1995 00:00:00 UTC; path=/;";

An example of javascript for creating a cookie:


An example of a cookie request javascript:


An example of javascript for checking a cookie:


Now, putting them all together in a web page (.html), when you access it, a pop-up window will appear that will ask for your name.
When we typed the name and pressed the OK button, this name was saved in the cookies.


If we close the browser, when we next visit this page, we will be welcomed by a box alert, which will greet us by using our cookie-saved name.


Cookie using PHP

An example of creating and displaying a cookie using PHP:


At the first opening of the web page, the PHP script will run and create the cookie. If we close the browser and reopen the web page, the cookie will be read and displayed in the browser as follows:


To delete the cookie, as well as to use javascript, we will set the expiration date once it has passed:

<< Prev
Next >>

Visit my websites: