Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ruby CGI Cookie

Ruby CGI Cookie

HTTP is a stateless protocol. But a commercial website needs to maintain session information across different pages.

For example, a user may need to navigate between pages during registration while ensuring that previously entered information isn't lost.

In this case, cookies solve the problem well for us.


How do cookies work?

Almost all web designers use cookies when designing websites, because they want to provide a friendlier, more human browsing environment for visitors while also collecting visitor information more accurately.

Writing and reading

The Cookies collection is a data collection attached to the Response object and the Request object; when using it, you need to prefix it with Response or Request.

The syntax for sending cookies to the client is usually:

When you set a cookie that doesn't exist, it's created on the client; if the cookie already exists, it's replaced. Since cookies are sent to the client as part of the HTTP headers, the code that sends cookies is generally placed before the tag of the HTML file sent to the browser.

If a user wants to read cookies, they must use the Request object's Cookies collection, as follows: Note that the browser can exchange cookie data with the server only before the server has downloaded any data to the browser; once the browser starts receiving downloaded data, the cookie exchange stops. To avoid errors, add response.Buffer=True at the beginning of the program and...

Collection properties


Handling cookies in Ruby

You can create an object named cookie, store text information in it, send that information to the browser, and call CGI.out to set the cookie header:

Example

!/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 return to this page and look up the cookie value, as follows:

Example

!/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

When a CGI::Cookie object is instantiated, it includes the following parameters:

Parameters Description
name Specifies the name of the cookie.
value Specifies the value of the cookie.
expire Specifies the expiration date of the cookie.
path Specifies the server path of the cookie.
domain Specifies the domain of the cookie.
secure Specifies whether the cookie is transmitted over a secure HTTPS connection.