Skip to content

Session Management Guide

Overview

cHttpServerSession provides HTTP session management functionality, supporting three storage types:

  • Memory Storage (SessionStorageMemory) - Default, in-process storage
  • File System Storage (SessionStorageFileSystem) - Persisted to file
  • Database Storage (SessionStorageDatabase) - Stored to database table

Session Storage Type Configuration

vb
Public Enum EnumSessionStorageType
    SessionStorageMemory = 0      ' Memory storage (non-persistent)
    SessionStorageFileSystem = 1   ' File system storage
    SessionStorageDatabase = 2     ' Database storage
End Enum

Quick Start

1. Memory Storage (Default)

vb
Private Sub Form_Load()
    Set Server = New cHttpServer
    
    ' Memory storage is default, no config needed
    Server.SessionStorageType = SessionStorageMemory
    
    Call Server.Start(8080)
End Sub

' Usage in controller
Public Sub Login(ctx As cHttpServerContext)
    ' Store user info after successful login
    ctx.Session("user_id") = "123"
    ctx.Session("username") = "John"
    ctx.Session.TimeOut = 30  ' 30 minutes timeout
    
    ctx.Response.Json Nothing, 0, "Login successful"
End Sub

Public Sub Profile(ctx As cHttpServerContext)
    ' Read session
    Dim userId As String
    userId = ctx.Session("user_id")
    
    If userId = "" Then
        ctx.Response.State401 "Not logged in"
        Exit Sub
    End If
    
    Dim profile As New Scripting.Dictionary
    profile("user_id") = userId
    profile("username") = ctx.Session("username")
    
    ctx.Response.Json profile
End Sub

Public Sub Logout(ctx As cHttpServerContext)
    ' Clear session
    ctx.Session.Abandon
    ctx.Response.Json Nothing, 0, "Logout successful"
End Sub

2. File System Storage

vb
Private Sub Form_Load()
    Set Server = New cHttpServer
    
    ' Configure file storage
    Server.SessionStorageType = SessionStorageFileSystem
    Server.SessionStoragePath = "C:\MyApp\Sessions"  ' Session file save directory
    Server.SessionCookieName = "MY_SESSIONID"         ' Cookie name
    
    Call Server.Start(8080)
End Sub

Session file format (JSON):

json
{
  "SessionID": "550e8400-e29b-41d4-a716-446655440000",
  "CreatedAt": "2026-05-17 10:30:00",
  "LastAccessedAt": "2026-05-17 10:35:00",
  "Timeout": 20,
  "Data": {
    "user_id": "123",
    "username": "John"
  }
}

3. Database Storage

vb
Private Sub Form_Load()
    Set Server = New cHttpServer
    
    ' Configure database connection
    If Server.Database.Connect(enumDbType.Mysql, "localhost,3306", "root", "password", "mydb") Then
        ' Configure database session storage
        Server.SessionStorageType = SessionStorageDatabase
        Server.SessionStoragePath = "user_sessions"  ' Table name
        Server.SessionCookieName = "SESSION_ID"
        
        Call Server.Start(8080)
    End If
End Sub

Database table structure:

sql
CREATE TABLE user_sessions (
    SessionID VARCHAR(255) PRIMARY KEY,
    SessionData TEXT,
    CreatedAt DATETIME,
    LastAccessedAt DATETIME,
    ExpiresAt DATETIME,
    INDEX idx_expires (ExpiresAt)
);

Session Properties Explained

Item (Default Property)

Get or set session data.

vb
' Store data
ctx.Session("key") = "value"
ctx.Session("user") = userObject  ' Objects supported

' Read data
Dim value As Variant
value = ctx.Session("key")

' Check existence
If ctx.Session.Exists("key") Then
    ' ...
End If

SessionID

Get session ID.

vb
Debug.Print "Session ID: " & ctx.Session.SessionID
' Output: 550e8400-e29b-41d4-a716-446655440000

TimeOut

Timeout in minutes, default 20 minutes.

vb
' Set 60 minutes timeout
ctx.Session.TimeOut = 60

' 0 means never expire
ctx.Session.TimeOut = 0

CreatedAt

Creation time.

vb
Debug.Print "Created at: " & ctx.Session.CreatedAt

LastAccessedAt

Last access time.

vb
Debug.Print "Last accessed: " & ctx.Session.LastAccessedAt

Session Methods Explained

Exists

Check if key exists.

vb
If ctx.Session.Exists("user_id") Then
    ' User is logged in
Else
    ' Not logged in
End If

Remove

Delete specified key.

vb
' Delete single key
ctx.Session.Remove("temp_data")

Clear

Clear all data (keep SessionID).

vb
ctx.Session.Clear

Abandon

Abandon current session (clear data and generate new SessionID).

vb
' Use when logging out
ctx.Session.Abandon

IsExpired

Check if session has expired.

vb
If ctx.Session.IsExpired Then
    ctx.Response.State401 "Session expired"
End If

Touch

Update last access time.

vb
' Manually refresh session time
ctx.Session.Touch

Complete Login Example

vb
' cAuthController.cls

' POST /login
Public Sub Login(ctx As cHttpServerContext)
    Dim username As String, password As String
    username = ctx.Request.Form("username")
    password = ctx.Request.Form("password")
    
    ' Validate credentials
    If Not ValidateUser(username, password) Then
        ctx.Response.Json Nothing, 1, "Invalid username or password"
        Exit Sub
    End If
    
    ' Get user info
    Dim user As Scripting.Dictionary
    Set user = GetUserInfo(username)
    
    ' Store in session
    ctx.Session("user_id") = user("id")
    ctx.Session("username") = user("username")
    ctx.Session("role") = user("role")
    ctx.Session.TimeOut = 120  ' 2 hours
    
    ' Return user info
    ctx.Response.Json user, 0, "Login successful"
End Sub

' GET /logout
Public Sub Logout(ctx As cHttpServerContext)
    ctx.Session.Abandon
    ctx.Response.Json Nothing, 0, "Logout successful"
End Sub

' GET /profile
Public Sub Profile(ctx As cHttpServerContext)
    ' Check login status
    If Not ctx.Session.Exists("user_id") Then
        ctx.Response.State401 "Please login first"
        Exit Sub
    End If
    
    ' Return user info
    Dim profile As New Scripting.Dictionary
    profile("user_id") = ctx.Session("user_id")
    profile("username") = ctx.Session("username")
    profile("role") = ctx.Session("role")
    
    ctx.Response.Json profile
End Sub

' Helper functions
Private Function ValidateUser(username As String, password As String) As Boolean
    ' Validation logic...
    ValidateUser = True
End Function

Private Function GetUserInfo(username As String) As Scripting.Dictionary
    Dim user As New Scripting.Dictionary
    user("id") = "123"
    user("username") = username
    user("role") = "admin"
    Set GetUserInfo = user
End Function

Session Security Recommendations

  1. Use HttpOnly Cookie: Prevent XSS attacks
  2. Set reasonable timeout: Don't set too long
  3. Use HTTPS: Prevent session ID interception
  4. Regular cleanup of expired sessions: Cleanup tasks needed for file/database storage
  5. Encrypt sensitive data: Don't store plaintext passwords in session
vb
' Security configuration example
' 1. Set cookie HttpOnly
With ctx.Cookies.Cookie("SESSIONID")
    .HttpOnly = True
    .Secure = True  ' Use in HTTPS
    .SameSite = "Strict"
End With

' 2. Session timeout setting
ctx.Session.TimeOut = 20  ' 20 minutes

Last Updated: 2026-05-17

VB6 and LOGO copyright of Microsoft Corporation