httpsessions topic
Working with HTTP Sessions
Declaration
httpsessionsDescription
HTTP sessions provide a way to maintain state across multiple HTTP requests from the same client.
The TCustomSession class manages session data using session IDs that are typically stored in cookies.
Sessions can be in different states: ssNew (newly created), ssActive (currently valid),
ssExpired (timed out), or ssResponseInitialized (response has been started).
Session variables are accessed using string key-value pairs through the Variables property.
program SessionExample;
{$mode objfpc}{$H+}
uses
httpdefs, SysUtils, Classes;
type
TMySession = class(TCustomSession)
private
FData: TStringList;
protected
function GetSessionVariable(const VarName: String): String; override;
procedure SetSessionVariable(const VarName: String; const AValue: String); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
constructor TMySession.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FData := TStringList.Create;
TimeOutMinutes := 30; // 30 minutes timeout
end;
destructor TMySession.Destroy;
begin
FData.Free;
inherited Destroy;
end;
function TMySession.GetSessionVariable(const VarName: String): String;
var
Index: Integer;
begin
Index := FData.IndexOfName(VarName);
if Index >= 0 then
Result := FData.ValueFromIndex[Index]
else
Result := '';
end;
procedure TMySession.SetSessionVariable(const VarName: String; const AValue: String);
begin
FData.Values[VarName] := AValue;
end;
var
Session: TMySession;
begin
Session := TMySession.Create(nil);
try
// Store session data
Session.Variables['username'] := 'john_doe';
Session.Variables['last_login'] := DateTimeToStr(Now);
// Retrieve session data
Writeln('Username: ', Session.Variables['username']);
Writeln('Last login: ', Session.Variables['last_login']);
Writeln('Session ID: ', Session.SessionID);
Writeln('Session cookie: ', Session.SessionCookie);
finally
Session.Free;
end;
end.An experiment, built from development snapshots. Not the official Free Pascal or Lazarus documentation.
