May 12, 2021 Ruby
The HTTP protocol is a stateless protocol. But for a business website, it needs to keep session information between pages.
If the user needs to jump the page during the website registration process, but also to ensure that the information department filled in before is lost.
Cookies in this case are a good way to help us solve the problem.
A cookie collection is a collection of data attached to a Response object and a Request object, which needs to be preceded by a Response or Request.
The syntax used to send cookies to clients is typically:
When you set up a collection of cookies that do not exist, they are created on the client and replaced if the cookie already exists. Since cookies are sent to the client as part of the header information transmitted by HTTP, the code for sending cookies to the client is generally placed before the TAG on the HTML file sent to the browser.
If the user wants to read cookies, the cookie collection of the Request object must be used by: It is important to note that the browser can only exchange cookies with the server until the server has not downloaded any data to the browser, and once the browser starts receiving the data downloaded by the server, the data exchange of cookies stops, in order to avoid errors, to add response to the program and in front of it. B uffer=True。
You can create an object called a cookie and store text information, send that information to your browser, and call CGI.out to set the head of the cookie:
#!/usr/bin/ruby require "cgi" cgi = CGI.new("html4") cookie = CGI::Cookie.new('name' => 'mycookie', 'value' => 'Zara Ali', 'expires' => Time.now + 3600) cgi.out('cookie' => cookie) do cgi.head + cgi.body { "Cookie stored" } end
Next we go back to this page and look for cookie values, as follows:
#!/usr/bin/ruby require "cgi" cgi = CGI.new("html4") cookie = cgi.cookies['mycookie'] cgi.out('cookie' => cookie) do cgi.head + cgi.body { cookie[0] } end
CGI: The cookie object is instantiated with the following parameters:
Parameters | Describe |
---|---|
name | Specify the name of the cookie. |
value | Specify the value of the cookie. |
expire | Specify the validity of the cookie. |
path | Specify the server path for the cookie. |
domain | The domain name that specifies the cookie. |
secure | Specify whether cookies are transmitted over a secure HTTPS connection. |