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 generationnew_session
:If thetrue
To create a new for the current sessionSession id
. If forfalse
, throughsession_id
use existingsession
identification. If this parameter is omitted, an existing session is used if available, otherwise a new one is created.database_manager
:For Savinsessions
can be a class ofCGI::Session::FileStore
orCGI::Session::MemoryStore
. Default isFileStore
.tmpdir
: ForFileStore
, is storage directory forsession
.prefix
: ForFileStore
, is the prefix of thesession
file.
Instantiation method
Serial number |
Method description |
---|---|
1 |
|
2 |
|
3 |
|
4 |
|