Ruby CGI Session
CGI::Session can save persistent session state for users and the CGI environment. Sessions need to be closed after use, which ensures data is written to storage. When the session is finished, you need to delete the data.
Examples
Visiting "/cgi-bin/test.cgi?bgcolor=red" will jump to a page with the specified background color.
Session data is stored in the server's temporary file directory. The prefix parameter specifies the prefix of the session, which will serve as the prefix of the temporary file. This way you can easily identify different session temporary files on the server.
CGI::Session Class
CGI::Session maintains the persistent state between a user and the CGI environment. Sessions can be in memory or on disk.
Class Methods
The Ruby class CGI::Session provides simple methods to create a session:
Starts a new CGI session and returns the corresponding CGI::Session object. The options can be an optional hash and can take the following values:
- session_key:The key name to save the session, defaults to _session_id.
- session_id:A unique session ID. Automatically generated.
- new_session:If true, create a new session ID for the current session. If false, use an existing session identifier via session_id. If this parameter is omitted, use the existing session if available; otherwise create a new one.
- database_manager:The class used to store sessions, which can be CGI::Session::FileStore or CGI::Session::MemoryStore. Defaults to FileStore.
- tmpdir:For FileStore, it is the storage directory for sessions.
- prefix:For FileStore, it is the prefix for session files.
Instance Methods
| No. | Method Description |
|---|---|
| 1 | [ ] Returns the value for the given key. See the example. |
| 2 | [ ]= Sets the value for the given key. See the example. |
| 3 | delete Calls the underlying database management's delete method. For FileStore, deletes the physical file containing the session. For MemoryStore, removes the session data from memory. |
| 4 | update Calls the underlying database management's update method. For FileStore, writes the session to disk. For MemoryStore, it has no effect. |