User Tools

Site Tools


Sidebar

Network and communication

k24:k24.6:k24.6.6:start

24.6.6 Session

When a request is made to an HTTP server, a client uses the service provided. This consists of the server returning the HTML source code of the web page specified in the URL to the client.There is no provision under the HTTP protocol to record the user who made the request, because HTTP is a stateless protocol. If there is a legitimate interest in assigning a request to exactly one user - for example, when logging into an admin area or filling a shopping basket or exchanging personalised data - then the server can manage the connection between the HTTP server and an HTTP client with the logged-in user. This is called starting a session. Under the following links you will find compact answers to the question of what a session is in computer science:

24.6.6.1 Class Session

24.6.6.2 Properties

The Session class has these properties:

PropertyDataTypeDescription
CookiePathStringReturns the path where the session cookie is stored at the client or sets the path. If CookiePath is empty, CGI[“SCRIPT_NAME”] is used for it, except that “/.” is replaced by “/” in this case.
IdStringReturns a session ID as a string. If no current session exists, NULL is returned. The format of a 'Session.Id' follows the syntax: <PREFIX>:<KEY>. <KEY> is a random hexadecimal number with 24 digits. If no prefix is specified, the IP address of the client is used as the prefix. this is the default.
ModifiedBooleanReturns true if the session has been modified or sets the truth value.
PrefixStringReturns or sets the prefix part of the session ID. If it is not set, the prefix is the IP address of the client.
SizeLongReads out the size of the cookie.
TimeoutFloatDetermines or sets the maximum duration of a session in seconds. The default value is 24*60*60 s = 86400 s, which corresponds to one day.
TypeStringReturns or sets the type of the file in which the session data is stored. Allowed are 'file' or 'sqlite'. If no type is specified, the default type is 'sqlite'. In this case, the session data file automatically receives the extension .db.
PathStringPath of the file in which session data is stored on the server. Beispiel: /tmp/gambas.1000/session/27_0_0_1_724EC44AC512F3B5BAAC948C.db.
UniqueBooleanReturns True if the session ID has been declared as unique or sets the corresponding truth value. Session.Unique = True ensures that there can only be one session for the same prefix.
KeysString[ ]Returns a list of all keys as a string array that are associated with a value in the session.

Table 24.6.6.2.1 : Properties of the Session class

24.6.6.3 Methods

The Session class has these four methods:

MethodDescription
Load()Loads a session from the server's hard disk. Either from the default path or from the user-defined path. The default path is /tmp/gambas.<user.id>/session.
Save()Saves a session to the server's hard disk. Either in the default path or in the user-defined path.
Abandon()Deletes the current session. The Session.Id is then zero. The session data file has a lifetime, which is determined by the property Session.Timeout.
Exist(Key As String)

Table 24.6.6.3.1 : Methods of the Session class

24.6.6.4 Session

You can use the class Session (gb.web) in a web application to manage a session on the server. However, a session is not created automatically, but only when an interactive web page provides methods to create and manage a session.

Create a session

A new session is created as soon as you save a session key value pair (session variable) for the first time and no session currently exists. You can check this because in this case the Session.Id property has the value NULL.

If Not Session.Id Then Session["user1"] = webtxbUserName.Text

Here is an example of a session ID when no prefix has been set. In this case, the client's IP address is used as the prefix: 10.254.3.151:CFA76E086C00E18CF07A8EC.

If the server has created a new session ID and stored it temporarily, then it informs the client about the session ID. The client must then send this session ID to the server with every further request (HTTP request) in order to guarantee the assignment request ↔ client.

Save a session

  • A session ID generated by the server is transmitted to the user's browser and stored there.
  • All data associated with a session under a session ID is stored by the web server in a specially created directory on the server. This is usually a temporary directory “…/tmp”. In addition to the session ID, the data stored there also contain other contents, such as a user ID or shopping basket data.

A session can be created the first time the programme is started and restored the next time the programme is started. This requires that the Session.Timeout property is set appropriately. The default is 86400 seconds (24*60*60s) or one day.

If the Cookie.Session property of the Cookie class (gb.qt4.webkit or gb.qt5.webkit) is set to True, then a (temporary) session cookie is set at the client. In this cookie with the assigned name, among other things, the Session.Id is stored in the. You can also set or delete a cookie with the two methods Response.SetCookie(…) and Response.RemoveCookie(…) of the Response class (gb.web).

Create, change and save session data.

In a session with a unique session ID, a value can be stored for each specified key. You can store as many key-value pairs as you need and also change their values at any time during the session.

A web form is often used to enter or change session data:

BILD
Figure 24.6.6.4.1: Login form

Only these data types are allowed for the values: array, native data types and collection:

Session["artikel1"] = "Tretroller"		' Session-Variable → anlegen und mit einem Wert belegen
Session["preis1"] = 47.90			' Session-Variable → anlegen und mit einem Wert belegen
Session["artikel1"] = "Dreirad"  		' Session-Variable → Wert ändern
Session["preis1"] = 30			     	' Session-Variable → Wert ändern
Session["liste1"] = ["Dreirad","rot","34€"]   	' Session-Variable → anlegen und mit Werten belegen
Session["artikel1"] = ""			' Session-Variable → löschen

If you pass an empty string to an existing key, then both the key and the value existing for this key are deleted in the temporary file!

The data of a session are automatically stored in a temporary SQLite database file with the following path on the server if you do not explicitly set the 'CookiePath' property:

"/tmp/gambas" &/ System.User.Id &/ "session" &/ Session.Id

Delete a session.

A session ID stored in a session cookie in the user's browser is automatically deleted when the user closes the browser completely. In Gambas, the Session.Abadon() method terminates the current session immediately.

Note: If you call Response.Begin() too early, the session cannot be created because the HTTP headers have already been sent. You then have two options:

  • You call Response.Begin() when you are sure that the session has already been created.
  • Set Response.Buffered to True so that the headers are not sent until you call Response.End().

24.6.6.5 Example 1

In the SmallWiki 1.0.1 project (Gamba's software farm), the login data is stored in a file passwd in the root directory and a new (admin) session is created with this source code:

If Request["login"] And If Request["password"] Then

'-- Eine bestehende Session wird beendet
    Session.Abandon()
    For Each sLine In Split(File.Load(Root &/ "passwd"), "\n")
      iPos = InStr(sLine, ": ")
      If iPos = 0 Then Continue
      sLogin = Trim(Left(sLine, iPos - 1))
      sPasswd = Trim(Mid$(sLine, iPos + 2))
      If sLogin = Request["login"] And If sPasswd = Request["password"] Then
     '-- Eine neue Session wird erzeugt, Daten werden abgespeichert und ein Session-Cookie gesetzt
         Session["login"] = sLogin
         Break
      Endif
    Next
Endif

These are the (formatted) response headers after the login with the user name and password. You can see these headers, for example, in the Firefox web browser after CTRL+R and then SHIFT+F9 in the 'Console' section:

    [1]  HTTP/1.0 200 OK
    [2]  127.0.0.1: D8053000E34641AA130A6A77
    [3]  Set-Cookie: GBSESSIONID=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/
    [4]  Set-Cookie: GBSESSIONID=127.0.0.1:D8053000E34641AA130A6A77;path=/;httponly
    [5]  Content-type: text/html;charset=utf-8

As you can see in line [3] and in the source code (Session.Abadon()), first an existing session is deleted, as the date is simply placed in the past. Then a new session is created and a session cookie is set→ in line [4]. With this source code:

<%If Session.Id Then%>
<% Print "<br>"; %>
<div class="box">
   <% Print "SESSION-ID = "; Session.Id; %>
   <% Print "<br>SESSION-TYP = "; Session.Type; %>
   <%
     Dim sPath As String
     Dim I As Integer
     Dim sChar As String
     Dim sName As String
     Dim sKey As String
     Dim aKeys As String[]
     Dim aVariant As Variant
 
     If Session.Id Then
        For I = 1 To Len(Session.Id)
          sChar = Mid(Session.Id, I, 1)
          If Not IsDigit(sChar) And If Not IsLetter(sChar) Then sChar = "_"
          sName &= sChar
        Next
     Endif
     Print "<br>";
     aKeys = Session.Keys
     For Each sKey In aKeys
       If Session.Exist(sKey) Then
          Print "SESSION.KEY.VALUE.PAIR: " & sKey & " => " & Session[sKey];
       Endif
     Next
     If Session.Type = "sqlite" Then
        Print "<br>SESSION-FILEPATH = "; Session.Path &/ sName & ".db";
     Else
        Print "<br>SESSION-FILEPATH = "; Session.Path &/ sName;
     Endif
   %>
   <% Print "<br>SESSION-SIZE = "; Session.Size; " Byte"; %>
   <% Print "<br>SESSION-TIMEOUT = "; Session.TimeOut; " s"; %>
   <%
     Print "<br>SESSION-COOKIE-PATH = "; Application.Root
     Print "<br>SESSION-COOKIE-PATH = "; CGI["SCRIPT_NAME"]
     Print "<br>SESSION-COOKIE-PATH = "; Session.CookiePath
 
     If Not Session.Prefix Then
        Print "<br>SESSION-PREFIX = Prefix is not set.";
     Else
        Print "<br>SESSION-PREFIX = "; Session.Prefix;
     Endif
   %>
</div>
 
<% Endif %>

these extended properties of the session were read out:

  [1] SESSION-ID = 127.0.0.1:C8319E3CF5607465BA28B531
  [2] SESSION-TYP = sqlite
  [3] SESSION.KEY.VALUE.PAIR: login => admin
  [4] SESSION-FILEPATH = /tmp/gambas.1000/session/127_0_0_1_C8319E3CF5607465BA28B531.db
  [5] SESSION-SIZE = 20480 Byte
  [6] SESSION-TIMEOUT = 86400 s
  [7] SESSION-COOKIE-PATH =
  [8] SESSION-COOKIE-PATH = /.
  [9] SESSION-COOKIE-PATH =
  [10] SESSION-PREFIX = Prefix is not set.

Lines 2 and 4 are interesting because they indicate that the session data is stored in a (temporary) SQLite database (with two tables: config and values). The different outputs in lines [7] to [9] are correct, because

  • Application.Root normalises CGI[“SCRIPT_NAME”] and returns “” if its value is “./” or “/”.
  • If Session.CookiePath is empty, the contents of CGI[“SCRIPT_NAME”] are used, except that “/.” is replaced by “/” in this case.

F12
Figure 24.6.6.5.1: View of cookie properties in Firefox - call with F12

The display of the (session) cookie properties in Firefox shows interesting details, especially in the right-hand section.

24.6.7 Example 2

The following example is very simple. The legitimate interest of the website operator is to display a different web page to a logged-in administrator with the user name 'admin' than to a user of the website with the user name 'user1'.

Here is an excerpt from the source code for the example:

Public Sub webbtnLogin_Click()
 
    If Not Trim(webtxbUserName.Text) Then
       Message.Warning("Attention!<br>The username is empty.")
       webtxbUserName.SetFocus(True)
    Else
       If webtxbUserName.Text = "user1" Then
          Session["user1"] = webtxbUserName.Text
          WebForm.Startup = "WebFormMain"
          WebformLogin.Reload()
       Else If webtxbUserName.Text = "admin" Then
          Session["admin"] = webtxbUserName.Text
          WebForm.Startup = "WebFormMain"
          WebformLogin.Reload()
       Else
          webtxbUserName.SetFocus(True)
       Endif
    Endif
 
End

This is how the login page shows up in a web browser:

Login
Figure 24.6.7.1: Login page

After a successful login, another web page is opened. Its content depends on the session created:

Public Sub WebForm_Open()
 
  WebTimer1.Start()
 
  If Session["admin"] Then
     WebHtml1.Text = "<h3>Hello " & Session["admin"] & "!</h3>"
     WebHtml1.Text &= "<br><p>Your service starts now ...</p>"
  Endif
 
  If Session["user1"] Then
     WebHtml1.Text = "<h3>Hello " & Session["user1"] & "!</h3>"
     WebHtml1.Text &= "<br><p>Note: The course 'Web Programming' starts next Friday at 14:30 (UTC) in the C-Building in room 123.</p><br>"
  Endif
 
End
 
Public Sub WebTimer1_Timer()
 
  If Session["admin"] Then weblblTime.Text = "Current time: " & Format(Now(), "hh:nn:ss")
  If Session["user1"] Then weblblTime.Text = "Current time: " & Format(DateAdd(Now(), gb.Second, -3600), "dd.mm.yyyy | hh:nn:ss (UTC)")
 
End
 
Public Sub webbtnLogout_Click()
  Session.Abandon()
  WebformMain.Reload()
End

Notice:

The Session.Abadon() method ends the current session with the logout. The set session cookie is deleted. The session file like 127_0_0_1_724EC44AC512F3B5BAAC948C.db in the path /tmp/gambas.1000/session, on the other hand, still exists as its (default) lifetime is 1 day.

User
Figure 24.6.7.2: User page

Admin
Figure 24.6.7.3: Admin page

In practice, permitted users are often captured via a web form to register on the website. The captured data (login name and password) is often stored in a database in a database table and supplemented with further data, which is again queried with a form on the registration page.

Web-Formular
Figure 24.6.7.4: Web form for login or registration

The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k24/k24.6/k24.6.6/start.txt · Last modified: 16.08.2022 (external edit)

Page Tools