Ruby CGI Session

CGI::Session can save persistent session state for users and CGI environments. It needs to be closed after the session is used. This ensures that 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< /span>"].to_s sess["lastaccess"] = Time.now if cgi['bgcolor'][0< /span>] =~ /[az]/ sess["bgcolor"] = cgi[' bgcolor'] end cgi.out{ cgi.html { cgi.body ("bgcolor" => Sess["bgcolor "]){ "The background of this page"< /span> + "changes based on the 'bgcolor' " + "each user has in session." + "Last access time: #{lastaccess}" } } }

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

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

CGI::Session class

CGI::Session maintains a persistent state of user and CGI environment. The session can be in memory or on the hard drive.

Class Method

The Ruby class Class CGI::Session provides an easy way to create a session:

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

Enable a new CGI session and return the corresponding CGI::Session object. The option can be an optional hash, which can be the following values:

  • session_key: The key name save session defaults to _session_id.
  • session_id: Unique session ID. Automatic generation
  • new_session: If true, creates a new Session id for the current session. If false, use the existing session ID with session_id. If this parameter is omitted, the existing session is used if available, otherwise a new one is created.
  • database_manager: The class used to save sessions, which can be CGI::Session::FileStore or CGI::Session::MemoryStore. The default is FileStore.
  • tmpdir: For FileStore, the wrong directory for the session.
  • prefix: For FileStore, the prefix for the session file.

Instantiation method

serial numbermethod description
1[ ]
Returns the value of the given key. View the instance.
2[ ]=
Set the value of the given key. View the instance.
Invoke the delete method of the underlying database management. For FileStore, delete the physical file containing the session. For MemoryStore, remove session data from memory.
Invoke the update method of the underlying database management. For FileStore, write the session to disk. No effect on MemoryStore.

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.