Skip to main content

Wuya Tutorial-Ruby CGI Sessions Function

Wuya Tutorial-Ruby CGI Sessions Function

CGI ::Session maintains a persistent state for web users in a CGI environment. The session should be closed after use as this ensures its data is written out to storage.

    #!/usr/bin/[ruby](/search?q=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 turn the individual user page red with each successive click until a new "bgcolor" is specified via the URL.

Session data is stored in a temporary file for each session, and the prefix parameter assigns a string to the file name to make it easily identifiable on the server's file system.

CGI::Session

CGI::Session maintains a persistent state for web users in a CGI environment. Sessions can reside in memory or be stored on disk.

class method

The Ruby class CGI::Session provides a single class method to create a session -

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

Starts a new CGI session and returns the corresponding CGI::Session object. option can be an optional hash that specifies one or more of the following -

  • session_key - The name of the key holding the session ID. The default value is _session_id.

  • session_id - Unique session ID. Automatic generated

  • new_session - If true, create a new session ID for this session. If false, use the existing session identified by session_id.

  • database_manager - Class used to save sessions; can be CGI::Session::FileStore or CGI::Session::MemoryStore. The default value is FileStore.

  • tmpdir - for FileStore, the directory for session files.

  • prefix - For FileStore, the prefix for the session filename .

method

Sr.No.Methods & Description
1[] Returns the value for the given key.
2[]= Sets the value of the given key.
3delete Call the delete method of the underlying database manager. For FileStore, delete the physical file containing the session. For MemoryStore, delete the session from memory.
4update Call the update method of the underlying database manager. For FileStore, write session data out to disk. Not valid for MemoryStore.

Detailed explanation of Ruby CGI Sessions function - [Wuya Tutorial](/search?q=Wuya Tutorial) NetworkWuya Tutorial Network provides CGI::Session to maintain a persistent state for Web users in a CGI environment. The session should be closed after use as this ensures...Wuya Tutorial-Ruby CGI Sessions Functionhttps://www.learnfk.com/ruby/ruby-cgi-sessions.html