CGI: VBScript CGI Property Class 1

VBScript CGI Property Class 1

This page revisits the Get CGI variables function.

The function provides a method to retrieve variables that were sent using either Post or Get. It is specific to Get and Post variables, obtaining other CGI variables requires another function.

This page covers a class that encapsulates both functions and to provide a unified interface. This CGI get property class allows any CGI variable to be obtained.

Class interface

A class’s interface allows you to interact with an object (component) created from the class blueprint. When designing an interface keep it simple; makes the class design quicker by reducing number of properties and methods to be designed and tested.

The CGI get property class is an example of this minimalist approach; requiring only a single method to retrieve a named variables value. During a page’s design you probably will want to view all variables passed to it. This is easy to implement, in terms of code and effort requires little overhead. The final interface consists of two methods:

  • object_name.getvar("variable name") - get value of named variable
  • object_name.list - display a list of all variables and values

CGI get property class

Complete class is shown on the right. With the exception of section Save process cgi variables the code has been covered on previous pages.

Constructor:
The constructor creates a local scripting dictionary where all CGI variables are saved. Variable names are stored as Keys corresponding item stores a variable’s value. After creating the dictionary it is populated using the subroutine save_cgi_variables.


Subroutine save_cgi_variables
This subroutine extracts all environment variables passed to the script. This has the following format.

Environment variable name = Environment variable value

A regex extracts the name and value parts ignoring the equals and stores them into the dictionary as keys and items respectively.

Finally subroutine extracts name and value pairs from the encoded data sent to with the page. This could be the result of either a Get or Post from a form. Equally may have been a Get posted from a page link.


Function getvar(key)
This function extracts a named variable from the dictionary and returns its value.


Subroutine list()
This subroutine is included purely for test purposes. During page development it allows all variables and their values to be easily listed.


Subroutine Class_Terminate()
This subroutine kills the dictionary when the class is destroyed.


=== Save Class ===

Next section provides an example of using the class it assumes the class has been saved in a separate file common_functions.vbs

  • In folder \www\vbs_test
  • Create a new file common_functions.vbs
  • Copy the class script on the right into this file
  • Save the file
Class cgi_get_var_class

 Private my_hash                                     'Local storage                     

 '--Constructor
 Private Sub Class_Initialize()                      'Set inital
   Set my_hash = CreateObject("Scripting.Dictionary")'Create associative array
   save_cgi_variables
 End Sub

 '-- Load cgi variables into local storage
 Sub save_cgi_variables
   Dim wshShell,wshUserEnv,strItem,objRegEx,colMatches,pair1,pair2
   Dim method,data_string,variable_array,cgi_variable,decoded_value,i
   Dim key_array,strKey

   '---Save process cgi variables
   Set wshShell   = CreateObject( "WScript.Shell" )   'Create shell object
   Set wshUserEnv = wshShell.Environment( "Process" ) 'Read process collection

   Set objRegEx = New RegExp                          'Create new reg obj
   objRegEx.Pattern = "^(.+?)=(.+)"                   'Pattern to search for
                                                      '(.+?) non-greedy (.+) greedy
   For Each strItem In wshUserEnv                     'Scan returned collection
    '--Perform regex 
    Set colMatches = objRegEx.Execute(strItem)        'Return Matched objects 
    If colMatches.Count < 0 Then                      'Match found
       pair1 = colMatches(0).SubMatches(0)            'Extract first capturing group
       pair2 = colMatches(0).SubMatches(1)            'Extract second capturing group
       my_hash.Add pair1,pair2                        'Save locally
       'WScript.Echo pair1 & "====" & pair2 & "<br />"'Test code
    End If
   Next                                               'get next item

   '---Save Post or Get variables
   method         = wshUserEnv("REQUEST_METHOD")      'Get method
   data_string    = wshUserEnv("QUERY_STRING")        'Get query string
   If method="POST" Then                              'If post data read stdin
     data_string  = WScript.Stdin.ReadAll             'Get post data
   End IF
   Set wshShell   = Nothing                           'clean-up
   Set wshUserEnv = Nothing

   variable_array = split (data_string, "&")          'split data save to array

   '--Save internally to my_hash - scripting dictionary
   for i = 0 to ubound(variable_array)                 'Scan array
    cgi_variable = split (variable_array(i), "=")      'Split variable-value pairs
    decoded_value1 = replace(cgi_variable(0), "+", " ")'Replace special character
    decoded_value1 = unescape(decoded_value1)          'Decode encoded value
    decoded_value2 = replace(cgi_variable(1), "+", " ")'Replace special character
    decoded_value2 = unescape(decoded_value2)          'Decode encoded value
    my_hash.add decoded_value1, decoded_value2         'Add to dictionary 
   next                                                'Get next pair
 End Sub

 '--Get named variable from my_hash
 Public Function getvar(key)
   getvar = my_hash.Item(key)     'return item
 End Function

 '--List all data in my_hash used for testing
 Public Sub list()
   Dim key_array, strKey
   key_array = my_hash.Keys                           'Get all Keys
   For Each strKey in key_array                       'Scan array
     Wscript.Echo strKey & " = " & my_hash.Item(strKey) & "<br />"
   Next
 End Sub

 '--Clean-up this class
 Private Sub Class_Terminate()
   'Cleaning up code.
   Set my_hash   = Nothing        'clean-up
 End Sub

End Class

Top

Test script 15 - Using the CGI get property class

The following provides a working example showing how to use the CGI get property class and how to include an external file containing this class.

Script format

  1. Just below the job opening tag add appropriate lines for all files you want to include. The get CGI variables class is contained in file common_functions.vbs hence we want to include this.

  2. This section contains the mandatory Content-type line. Following this is the page title.

  3. This strictly speaking is not the start of anything! It was added to highlight a distinct section it’s just a continuation of the script.

First a new object named cgi is created using the New directive and the class template cgi_get_var_class.


Variables passed to the page are obtained using the dot operator and method getvar for example cgi.getvar("Hidden"). These are output to the page using WScript.Echo


Next follows two forms for sending Post and Get data respectively.


Lastly a link has been added to show how an anchor tag can be used for sending data.


Run script

  • Create a new file class_cgi_2.wsf
    with content as shown on right.
  • Save to test folder \www\vbs_test
  • Start Apache if not already running
  • Enter: http://localhost:8081/vbs_test/class_cgi_2.wsf into browser.
'!c:/windows/system32/cscript //nologo

<job>
'--1) Include any external files
<script language="VBScript" src="common_functions.vbs"/>

'--2) Main script ---
<script language="VBScript">
Option Explicit ' Force explicit variable declaration.
Wscript.Echo "Content-type: text/html"&vbLF&vbLF
Wscript.Echo "<title>Test 15</title>"

'--3) Start page code ---
Dim cgi
set cgi  = New cgi_get_var_class     'Create new object
'cgi.list                             '** Test code **

'Display form variables
Wscript.Echo  "Hidden var    = " & cgi.getvar("Hidden")  & "<br />"
Wscript.Echo  "Text box var  = " & cgi.getvar("text box")& "<br />"
Wscript.Echo  "Link test var = " & cgi.getvar("alink")
Wscript.Echo  "<br /><br />"

'--Form method post
WScript.Echo  "<form method=""POST"" action=""class_cgi_2.wsf"" >"
WScript.Echo  "  <input type=""text"" name=""text box"" value=""Post Test"">"
WScript.Echo  "  <input type=""hidden"" name=""Hidden"" value=""Test 15"">"
WScript.Echo  "  <input type=""submit"" value=""Post"">"
WScript.Echo  "</form>"

'--Form method get
WScript.Echo  "<form method=""GET"" action=""class_cgi_2.wsf"" >"
WScript.Echo  "  <input type=""text"" name=""text box"" value=""Get Test"">"
WScript.Echo  "  <input type=""hidden"" name=""Hidden"" value=""Test 15"">"
WScript.Echo  "  <input type=""submit"" value=""Get"">"
WScript.Echo  "</form>"

WScript.Echo  "<a href=""class_cgi_2.wsf?alink=my page 2"">Test Link</a>"
</script>
</job>

Enter data into a form’s text box and click corresponding test button. Note hidden and text box variable values are displayed but not the Test Link data. Click the Test Link, only its variable data is displayed and not the form data variables these are cleared.

Top

Summary

The CGI get property class allows you to easily obtain any CGI variable however currently it is lacking cookie variables these are covered next.

Where to next

Next page covers expanding the CGI get property class to include cookie variables.

Top