English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Ruby CGI Session

CGI::Session can save persistent session states for users and CGI environments. After using the session, it needs to be closed to ensure that data is written to storage. When the session is completed, you need to delete the data.

Online 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}"
    }
  }
}

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

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

CGI::Session class

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

Class methods

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

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

Enables a new CGI session and returns the corresponding CGI::Session object. Options can be an optional hash, which can be one of the following values:

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

  • session_id:  A unique session ID. Automatically generated

  • new_session: If true, a new Session id will be created for the current session. If false, the existing session will be identified using session_id. If this parameter is omitted, an existing session will be used if available, otherwise a new one will be created.

  • database_manager: A class used to save sessions, which can be CGI::Session::FileStore or CGI::Session::MemoryStore. The default is FileStore.

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

  • prefix: For FileStore, the prefix for session files.

Example Method

Serial NumberMethod Description
1[ ]
Return the value of the given key. See examples.
2[ ]=
Set the value of the given key. See examples.
3delete
Invoke the delete method of the underlying database management. For FileStore, delete the physical file containing the session. For MemoryStore, remove the session data from memory.
4update
Invoke the update method of the underlying database management. For FileStore, write the session to disk. For MemoryStore, no effect.