Ruby CGI Session


Release date:2023-11-02 Update date:2023-11-02 Editor:admin View counts:448

Label:

Ruby CGI Session

CGI::Session Persistent session state can be saved for the user and the CGI environment, and the session needs to be closed after use, which ensuresthat the data is written to the storage, and you need to delete the data when the session is complete.

Example

#!/usr/bin/rubyrequire'cgi'require'cgi/session'cgi=CGI.new("html4")sess=CGI::Session.new(cgi,
"session_key"=>"a_test","prefix"=>"rubysess.")lastaccess=sess["lastaccess"].to_ssess["lastaccess"]=
Time.nowifcgi['bgcolor'][0]=~/[a-z]/sess["bgcolor"]=cgi['bgcolor']endcgi.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}"} } }

Visit "/cgi-bin/test.cgi?bgcolor=red" Jumps to the page that specifies the background color.

Session data exists in the server’s temporary file directory prefix parameter specifies the prefix for the session and will be used as the 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 between the user and the CGI environment. The session can be in memory or on the hard drive.

Class method

Ruby class Class CGI::Session provides a simple way to create 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 with the following values:

  • session_key :Key name save session defaults to \_session_id .

  • session_id :Unique session ID Automatic generation

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

  • database_manager :For Savin sessions can be a class of CGI::Session::FileStore or CGI::Session::MemoryStore . Default is FileStore .

  • tmpdir : For FileStore , is storage directory for session .

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

Instantiation method

Serial number

Method description

1

[ ] Returns the value of the given key. View the instance.

2

[ ]= Sets the value of the given key. View the instance.

3

delete Call the delete method of the underlying database management. ForFileStore, delete the physical file that contains session. For MemoryStore,remove session data from memory.

4

update Call the update method of the underlying database management. ForFileStore, write the session to disk. It has no effect on MemoryStore.

Powered by TorCMS (https://github.com/bukun/TorCMS).