Javascript how to pass values ​​to cookies. Cookies - installation


Last update: 11/1/2015

One of the possibilities for saving data in javascript is the use of cookies. To work with cookies, the document object uses the cookie property.

To set cookies, just assign the document.cookie property a string with cookies:

document.cookie = "login=tom32;";

In this case, a cookie is set called "login" and has the value "tom32". And in most browsers we can view it, find out all the information about it, and then we can use it in the application:

A cookie string takes up to six different parameters: cookie name, value, expiration date, path, domain, and secure. Only two parameters were used above: the cookie name and the value. That is, in the case of the line "login=tom32;" The cookie has the name login and the value tom32.

But such cookies have a very limited lifespan: if you do not explicitly set the expiration date, the cookie will be deleted when the browser is closed. This situation may be ideal for those cases where you need to delete all information after you finish working with a web application and close the browser. However, this behavior is not always appropriate.

And in this case, we need to set the expires parameter, that is, the expiration date of the cookies:

That is, the login cookie expires on Monday, August 31, 2015 at 00:00. The format of the expires parameter is very important. However, it can be generated programmatically. To do this, we can use the toUTCString() method of the Date object:

Var expire = new Date(); expire.setHours(expire.getHours() + 4); document.cookie = "login=tom32;expires=" + expire.toUTCString() + ";";

In this case, the cookie will expire for 4 hours.

If we need to install cookies for a specific path on the site, then we can use the path parameter. For example, we want to set cookies only for the path www.mysite.com/home:

In this case, for other paths on the site, for example, www.mysite.com/shop, these cookies will not be available.

If we have multiple domains on our site and we want to set cookies directly for a specific domain, then we can use the domain parameter. For example, we have a subdomain on our website blog.mysite.com:

Document.cookie = "login=tom32;expires=Mon, 31 Aug 2015 00:00:00 GMT;path=/;domain=blog.mysite.com;";

The path=/ parameter specifies that cookies will be available for all directories and paths of the blog.mysite.com subdomain.

The last parameter - secure specifies the use of SSL (SecureSockets Layer) and is suitable for sites using the https protocol. If this parameter is set to true , cookies will only be used when establishing a secure ssl connection. By default, this parameter is false.

Document.cookie = "login=tom32;expires=Mon, 31 Aug 2015 00:00:00 GMT;path=/;domain=blog.mysite.com;secure=true;";

Receiving cookies

To easily retrieve cookies from the browser, just access the document.cookie property:

Var expire = new Date(); expire.setHours(expire.getHours() + 4); document.cookie = "city=Berlin;expires="+expire.toUTCString()+";"; document.cookie = "country=Germany;expires="+expire.toUTCString()+";"; document.cookie = "login=tom32;"; document.write(document.cookie);

Three cookies have been set here, and the browser will show us all these cookies:

The retrieved cookies do not include the expires, path, domain, and secure parameters. Additionally, the cookies themselves are separated by semicolons, so you still need to do some conversion to get their name and value:

Var cookies = document.cookie.split(";"); for(var i=0; i

When using Cookies, please be aware that Cookies must be set before the first output of information to the browser (for example, by the echo operator or the output of any function). Therefore, it is advisable to set Cookies at the very beginning of the script. Cookies are set using a specific server header, and if the script outputs anything, it means the body of the document begins. As a result, Cookies will not be installed and a warning may be displayed. To check whether Cookies were installed successfully, you can use the following method:

The SetCookie() function returns TRUE if the Cookie was successfully set. If the Cookie cannot be set, SetCookie() will return FALSE and possibly a warning (depending on PHP settings). Example of unsuccessful Cookie installation:

The cookie could not be set because we printed the string "Hello" to the browser before sending the Cookie header.

Reading Cookies Values

Accessing Cookies and their values ​​is quite simple. They are stored in the superglobal arrays $_COOKIE and $HTTP_COOKIE_VARS .

The values ​​are accessed by the name of the installed Cookies, for example:

echo $_COOKIE["my_cookie"];
// Displays the values ​​of the installed Cookie "My_Cookie"

An example of setting a Cookie and then reading it:

In the example considered, the first time the script is accessed, the Cookie "test" is set with the value "hello". When you access the script again, the Cookie value "test" will be displayed, that is, the string "Hello".

When reading Cookies values, pay attention to checking for the existence of Cookies, for example using the isset() operator. Either by suppressing error output using the @ operator

Here is an example of how to build a counter for the number of page loads using Cookies:

Removing Cookies

Sometimes it becomes necessary to delete Cookies. This is not difficult to do; you just need to set the Cookie again with an identical name and an empty parameter. For example:

Setting the Cookies array and reading it

We can set the Cookies array using square brackets in the Cookies names, and then read the Cookies array and the values ​​of that array:

The benefits of using Cookies are undeniable. However, there are also some problems with their use. The first of these is that the visitor can block the browser from accepting Cookies or simply delete all or part of the Cookies. Therefore, we may have some difficulty identifying such visitors.



>
If you have any other questions or something is not clear - welcome to our

Prepared by: Andrey Kosyak Date of publication: 12/22/2010

In the first article Cookies - we bake cookies, we looked at cookies from a long distance, so if you understand the general concepts and purpose of cookies, you can proceed directly to baking (I also got an oven), therefore, put on a culinary cap and come closer. Let's bake!

Art. Preparation

You already know that a cookie is a string, and you also know what a cookie looks like through the eyes of a browser. When installed in the browser, the cookie looks like the same line:

"cookieName = cookieValue; expires = Fri, 21 Jan 2021 06:10:00 GMT; path = /; domain = lessons.site; secure = true; "

The conditions for the existence of cookies are specified by five parameters (key=value pairs) (IMPORTANT! Each must be followed by a separator character ";"), consider them:

Cookie filling

"cookieName =cookieValue;" is the main cookie parameter; without it, the cookie loses its meaning. Here cookieName is the unique name for the cookie and cookieValue is the information (value) it will store. Looking ahead a little, I will say that the value can be anything, any structure of stored data that is convenient for you (even JSON), as well as any symbols. The only pair that is required when setting cookies.

Lifetime

"expires = Fri, 21 Jan 2021 06:10:00 GMT" - this pair, although optional, plays a very important role, along with the first. This parameter determines the lifetime of the cookie, namely, to the nearest second, on the specified date, the cookie will “live for a long time.” If this parameter is not specified, the cookie will only be valid for the duration of the session, which means that when the browser is closed, it will be deleted.

An important point is the date format. The date must be specified in text format ONLY (Fri, 21 Jan 2021 06:10:00 GMT). Again, looking ahead a little, I will say that the Date object will help us with this; it has all the necessary tools.

Installation path

"path =/" - this parameter specifies the path (directory) for which the cookie is valid. Now path has the value "/", this is nothing more than the root directory, so the cookie will be readable by absolutely all directories on the site. If access to the cookie should be limited, then we simply do not specify the path parameter or specify the general parent directory in it, and the cookie will be installed for a specific directory, but the specifics are such that the cookie will be available to all its subdirectories, at the same time - not visible to adjacent and parent directories.

What is this for? Let's imagine an elementary situation: an Internet cafe, first the user Vasya came and worked with his page on the social network, and after him Petya came and, on the same computer, on the same network, worked with his page. The participants' pages are located in the same domain, but, as a rule, are located in adjacent directories. For example: Vasya’s page is http://socset.com/vasya, Petya’s page is http://socset.com/petya. You can imagine what chaos there will be if cookies are installed in the root directory: Vasya will be able to operate with Petya’s cookies and vice versa. I think neither one nor the other will like this option. Therefore, in this case, it would be appropriate if the cookies were tied only to the directory of a specific user, and therefore to all its subdirectories.

Domain

"domain = lessons.site" - this pair specifies the domain in which the cookies are valid. As a rule, it is rarely necessary to use it explicitly. The situation with this parameter is similar to the situation with the path parameter, with the difference that in Domain we operate with domains and subdomains and not directories. That is, in this case, cookies are set for the lessons..site subdomain. If the parameter is not specified, then the domain address of the document is used by default.

Safety

"secure =true" — security parameter. If this parameter is set to true, the browser will only send cookies to the server that requests them over a secure channel (SSL). This option is also rarely used. Defaults to false.

The first pancake is lumpy?

Now let's try to treat our browser with a cookie. The document.cookie object will help us with this:

Document.cookie = "firstCookie=First pancake lumpy?; expires=Fri, 21 Jan 2021 06:10:00 GMT; path=/;";

The result can be seen by opening the cookies section in your browser, or simply:

Document.cookie = "firstCookie=First pancake lumpy?; expires=Fri, 21 Jan 2021 06:10:00 GMT; path=/;"; alert(document.cookie);

And not lumpy at all! Everything is buzzing and in place.

The note

I would like to draw your attention to the peculiarity of WebKit browsers. They refuse to set cookies if the document is opened locally. I usually use a local server in such cases; it will also be needed when working with AJAX. Therefore, as they say, a must have! For example, Denwer (link at the end of the article).

More cookies

We sorted out one cookie. But what if you need to store, for example, data from a form (login, e-mail, phone number, etc.)? In this case, you can do this:

Document.cookie = "myLogin=My login; expires=Fri, 21 Jan 2021 06:10:00 GMT; path=/;"; document.cookie = " [email protected]; expires=Fri, 21 Jan 2021 06:10:00 GMT; path=/;"; document.cookie = "myPhone=1234567; expires=Fri, 21 Jan 2021 06:10:00 GMT; path=/;";

Thus, we have three cookies that store the login, email and phone number, respectively. But do you remember about the restrictions on the number of cookies from one domain, as well as their total number? This means that in this way we can only store a limited number of values ​​for fields. And if such a limitation “ties” our hands, we can do this:

Var formData = escape("My login; [email protected];1234567"); document.cookie = "myFormCookie="+formData+"; expires=Fri, 21 Jan 2021 06:10:00 GMT; path=/;";

As a result, we have 1 usable cookie space. I “glued” all the data into one variable and separated them with the symbol “;”, however, any symbol can be used as a separator inside the variable, this is our initiative, here we just need to make sure that this separator does not appear in the field values, otherwise difficulties will arise later when you need to read them. In this case, of course, you still need to remember about the cookie size limit (4kb).

Why escape function? It's quite simple, it encodes the cookie value into hexadecimal representation. For what? Firstly, the browser sends cookies to the server, and in order for the data to be read equally on servers under any system, this encoding is used. Secondly, if we use the delimiter ";" in a variable with field values, if we do not encode this string, then the cookie, at least, will simply not be set correctly, because the separator is ";" used to separate the parameters of the cookie itself. This point should be taken into account and, henceforth, used by default when transmitting information (cookies, AJAX).

"...and you can't stop time for a moment"

Now let's look at the expires parameter. The inconvenience is that until this moment we set the lifetime for cookies manually. But, in real conditions, this approach is practically not applicable. At a minimum, because with each subsequent visit to the site, the lifetime of cookies should be extended by some fixed line, which, in general, is justified and logical. Therefore, the Date object will completely help us in this matter:

Var formData = escape("My login; [email protected];1234567"); cookieExp = new Date(); // create a Date object cookieExp.setMonth(cookieExp.getMonth()+1); // set the current month and add another one to it document.cookie = "myFormCookie="+ formData+"; expires="+cookieExp.toGMTString()+"; path=/;";

With these actions, we set the cookie lifetime to exactly 1 month. I won’t go into detail about the Date object in this article, I’ll just describe the scheme for setting the date:

  • line 2: declare cookieExp as a Date object. CookieExp now contains the current date;
  • line 3: resetting to cookieExp of the month. Using the getMonth method, we retrieve the current month and add another one to it. As a result, the next month will be recorded in cookieExp;
  • line 6: in this line we use the toGMTString() method to convert the date to text format;

So, depending on what lifetime you want to set for the cookie, you can use other Date object methods, from get/setMilliseconds() to get/setFullYear() (from getting/setting milliseconds to getting/setting year).

There is no point in demonstrating the remaining parameters; besides, their default values ​​in the vast majority of cases will suit you just fine.

Conclusion

As you can see, installing cookies is not something supernatural, you just need to remember (how many times I’m repeating myself :)) about the restrictions and everything will be tip-tip, well, or topi-top. The next material will be about how to get our cookies out of the oven. This is where you have to think a little.

Where to go
  • next - Cookies - extraction
  • previous -






2024 gtavrl.ru.