Ruby CGI Sessions


CGI::Session can save persistent session state for the user and the CGI environment. The session needs to be closed after use. This ensures that the data is written to the storage. When the session is completed, you need to delete the data.

#!/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}"
    }
  }
}

Accessing "/cgi-bin/test.cgi?bgcolor=red" will jump to the page with the specified background color.

Session data exists in the temporary file directory of the server. The prefix parameter specifies the prefix of the session, which will be used as the prefix of the temporary file. This way you can easily identify different session temporary files on the server.


CGI::Session Class

CGI::Session maintains persistent state between the user and the CGI environment. Sessions can be in memory or on hard disk.

Class methods

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

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

Enable a new CGI session and return the corresponding CGI:: Session object. Options can be optional hashes and can be the following values:

  • session_key: Key name to save the session Defaults to _session_id.

  • session_id: Unique session ID. Automatically generate

  • new_session: If true, create a new Session id for the current session. If false, use the existing session ID via session_id. If this parameter is omitted, an existing session is used if available, otherwise a new one is created.

  • database_manager: Class used to save sessions, which can be CGI::Session::FileStore or CGI::Session::MemoryStore. Defaults to FileStore.

  • tmpdir: For FileStore, the error storage directory for the session.

  • prefix: For FileStore, it is the prefix of the session file.

Instantiation method

Serial numberMethod description
1[ ]
Returns the value of the given key. See examples.
2[ ]=
Set the value of the given key. See examples.
3delete
Call the delete method of the underlying database management. For FileStore, delete the physical file containing the session. For MemoryStore, remove session data from memory.
4update
Call the update method of the underlying database management. For FileStore, write the session to disk. It has no effect on MemoryStore.