Easy Tutorial
❮ Ruby Class Ruby Intro ❯

Ruby CGI Session

CGI::Session can maintain persistent session states for users and the CGI environment. Sessions need to be closed after use to ensure data is written to storage. Once the session is completed, you should delete the data.

Example

#!/usr/bin/ruby

require 'cgi'
require 'cgi/session'
cgi = CGI.new("html4")

sess = CGI::Session.new( cgi, "session_key" => "a_test",
                              "prefix" => "rubysess.")
lastaccess = sess["lastaccess"].to_s
sess["lastaccess"] = Time.now
if cgi['bgcolor'][0] =~ /[a-z]/
  sess["bgcolor"] = cgi['bgcolor']
end

cgi.out{
  cgi.html {
    cgi.body ("bgcolor" => sess["bgcolor"]){
      "The background of this page"    +
      "changes based on the 'bgcolor'" +
      "each user has in session."      +
      "Last access time: #{lastaccess}"
    }
  }
}

Visiting "/cgi-bin/test.cgi?bgcolor=red" will redirect to a page with the specified background color.

Session data is stored in the server's temporary file directory, and the prefix parameter specifies the prefix for the session, which will be used as the prefix for temporary files. This allows you to easily identify different session temporary files on the server.


CGI::Session Class

CGI::Session maintains persistent states for users and the CGI environment. Sessions can be stored in memory or on disk.

Class Methods

The Ruby class CGI::Session provides simple methods to create a session:

CGI::Session::new( cgi[, option])

This initializes a new CGI session and returns the corresponding CGI::Session object. Options can be an optional hash with the following values:

Instance Methods

No. Method Description
1 [ ] <br>Returns the value for the given key. See example.
2 [ ]= <br>Sets the value for the given key. See example.
3 delete <br>Calls the delete method of the underlying database manager. For FileStore, it deletes the physical file containing the session. For MemoryStore, it removes the session data from memory.
4 update <br>Calls the update method of the underlying database manager. For FileStore, it writes the session to disk. For MemoryStore, it has no effect.
❮ Ruby Class Ruby Intro ❯