CGI: Get CGI variables

From The Uniform Server Wiki
Jump to navigation Jump to search

Get CGI variables

Writing CGI scripts using JavaScript will require access to CGI variables.

A VBScript to perform this task was covered on the URL encoding page. WSF allows you to use functions written in either VBScript or Jscript. Unfortunately there is a time penalty to pay hence write your CGI script exclusively in either VBScript or Jscript.

This page covers a JScript version of the Get CGI variables function.


VBScript - Get CGI variables function

VBScript:

For consistency the VBScript Get CGI variables function is reproduced on the right.

'=== Function Get CGI variables ===============================================
Function cgi_variables()
 Set cgi_hash = CreateObject("Scripting.Dictionary")'Create associative array

 '--Access environment variables and post data
 Set wshShell   = CreateObject( "WScript.Shell" )   'Create shell
 Set objEnv     = wshShell.Environment( "Process" ) 'Access enviroment
 method         = objEnv("REQUEST_METHOD")          'Get method
 data_string    = objEnv("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 objEnv     = Nothing

 '--Save variable-value pairs to array
 variable_array = split (data_string, "&")          'split and save to array

 '--Populate the 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

 Set cgi_variables = cgi_hash                       'Return dictionary
End Function
'=========================================== End Function Get CGI variables ===

How to use:

An example of its use is shown on the right.

'--Example of cgi dictionary function use.
Set cgi = cgi_variables()         'Get cgi dictionary 
wscript.echo cgi.item("text")     'Display text var
wscript.echo cgi.item("Language") 'Display language var

Top

Test Script 12 - Raw data form example

This script contains two forms these send data either using GET or POST. It displays the method used and data sent. Data is displayed raw it is not decoded or separated into variables.

  • Create a new file test12.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/test12.wsf into browser.

Click either the Get or Post buttons encoded data sent to the server is displayed.

Default string entered:

Cat  & dog=50a%

There is a hidden string:

English

This gives encoded string as shown below:

text=Cat++%26+dog%3D50a%25&Language=English
'!c:/windows/system32/cscript //nologo
<job>
<script language="JScript">
  WSH.Echo("Content-type: text/html \n\n");

  WSH.Echo("<html>");
  WSH.Echo("<title>Test 12</title>");
  WSH.Echo("<body>");

  // Get WshShell object.
  var WshShell = WScript.CreateObject("WScript.Shell");

  // Get collection by using the Environment property.
  var objEnv = WshShell.Environment("Process");

  // Get CGI data
  var method = objEnv("REQUEST_METHOD");      //set to request method
 
  // Read post data
  var post_data = ""                           // Rest post data string  
  if (method=="POST"){                         // If POST read stdin
    while (!WScript.StdIn.AtEndOfStream){      // Loop until no more data
     post_data += WScript.StdIn.ReadAll();     // Build string
    }
  }

  // Display CGI data
  WSH.Echo("Method: "       + method                 + "<br />");
  WSH.Echo("Query String: " + objEnv("QUERY_STRING") + "<br />");
  WSH.Echo("Post data: "    + post_data              + "<br />");
  WSH.Echo("<br />");

  // Form method post
  WSH.Echo("<form method=\"POST\" action=\"test12.wsf\" >");
  WSH.Echo("  <input type=\"text\" name=\"text\" value=\"Cat  & dog 50a%\">");
  WSH.Echo("  <input type=\"hidden\" name=\"Language\" value=\"English\">");
  WSH.Echo("  <input type=\"submit\" value=\"Post\">");
  WSH.Echo("</form>");

  // Form method get
  WSH.Echo("<form method=\"GET\" action=\"test12.wsf\" >");
  WSH.Echo("  <input type=\"text\" name=\"text\" value=\"Cat  & dog 50a%\">");
  WSH.Echo("  <input type=\"hidden\" name=\"Language\" value=\"English\">");
  WSH.Echo("  <input type=\"submit\" value=\"Get\">");
  WSH.Echo("</form>");

  WSH.Echo("</body>");
  WSH.Echo("</html>");
</script>
</job>

Top

Test Script 13 - Function Get CGI variables

This script contains two forms these send data either using GET or POST. It uses a function to separate variables sent and decodes their corresponding values. These are then displayed.

Click either the Get or Post buttons, encoded and decoded data is displayed.

Note: After testing. The encoded data display section can be removed from the function.


Function cgi_variables():

  • Received data is split using data_str.split ("&") and the result saved to array variable_array.
  • This array is scaned using a for loop. Each variable-value pair is split using pair_str.split("=")
  • The cgi_variable(0) part is used directely for the index while cgi_variable(1) requires further processing.
  • First the special character "+" is replaced with a space and the result decoded.
  • The index cgi_variable(0) and value decoded are added to the associative array.
  • Finally the function returns the associative array cgi_hash
'!c:/windows/system32/cscript //nologo
<job>
<script language="JScript">
  WSH.Echo("Content-type: text/html \n\n");

  WSH.Echo("<html>");
  WSH.Echo("<title>Test 13</title>");
  WSH.Echo("<body>");

//=== Function Get CGI variables ==============================================
function cgi_variables(){
  var cgi_hash = new Array();  //Create associative array

  var data_str =""                                      //reset received data
  var WshShell = WScript.CreateObject("WScript.Shell"); //Create shell object
  var objEnv   = WshShell.Environment("Process");       //Access enviroment
  var method   = objEnv("REQUEST_METHOD");              //set to send method
 
  if (method=="POST"){                         // If POST 
    while (!WScript.StdIn.AtEndOfStream){      // Read data from stdin
     data_str += WScript.StdIn.ReadAll();      // Build string
    }                                          // Loop until no more data
  }
  else{                                        // Method was GET
    data_str = objEnv("QUERY_STRING");         // Set data to query string
  }
 
//***** Test code **********************************************
  // Display CGI data
  WSH.Echo("Method: "       + method                 + "<br />");
  WSH.Echo("Data string: "  + data_str               + "<br />");
//***** Test code ***********************************************

 if (data_str ==""){                            //If string empty
   return cgi_hash;                             //Return the blank array
 }

  // Split and save all variable-value pairs to array
  var variable_array = data_str.split ("&");  

  for (i=0;i<variable_array.length;i++){      // Scan array
    var pair_str = variable_array[i];         // Get variable-value pairs
    var cgi_variables = pair_str.split("=");  // Split into variable/value

    var decoded = cgi_variables[1];           // Get encoded value
    decoded = decoded.replace(/\+/gi, " ");   // Replace special character +
    decoded = unescape(decoded);              // Complete the decoding

    cgi_hash[cgi_variables[0]] = decoded;     // Add to associative array 
  }                                           // index set to variable  
  return cgi_hash;                            //Return the array
} //End function
//========================================== End Function Get CGI variables ===

  // Example of function use:
  var cgi_vars = new Array;       // Create new array
  cgi_vars     = cgi_variables(); // Get CGI variables
     //Use square index brackets 
  WSH.Echo("Text value: " + cgi_vars["text"]     + "<br >"); //Print value
  WSH.Echo("Language: "   + cgi_vars["Language"] + "<br >"); //Print value
    //Or use the dot operator
  WSH.Echo("Text value: " + cgi_vars.text        + "<br >"); //Print value
  WSH.Echo("Language: "   + cgi_vars.Language    + "<br >"); //Print value
  WSH.Echo("<br >"); //Print blank line

  // Form method post
  WSH.Echo("<form method=\"POST\" action=\"test13.wsf\" >");
  WSH.Echo("  <input type=\"text\" name=\"text\" value=\"Cat  & dog 50a%\">");
  WSH.Echo("  <input type=\"hidden\" name=\"Language\" value=\"English\">");
  WSH.Echo("  <input type=\"submit\" value=\"Post\">");
  WSH.Echo("</form>");

  // Form method get
  WSH.Echo("<form method=\"GET\" action=\"test13.wsf\" >");
  WSH.Echo("  <input type=\"text\" name=\"text\" value=\"Cat  & dog 50a%\">");
  WSH.Echo("  <input type=\"hidden\" name=\"Language\" value=\"English\">");
  WSH.Echo("  <input type=\"submit\" value=\"Get\">");
  WSH.Echo("</form>");

  WSH.Echo("</body>");
  WSH.Echo("</html>");
</script>
</job>

Top

JScript - Get CGI variables function

For consistency the JScript Get CGI variables function is shown on the right.

//=== Function Get CGI variables ==============================================
function cgi_variables(){
  var cgi_hash = new Array();  //Create associative array

  var data_str =""                                      //reset received data
  var WshShell = WScript.CreateObject("WScript.Shell"); //Create shell object
  var objEnv   = WshShell.Environment("Process");       //Access enviroment
  var method   = objEnv("REQUEST_METHOD");              //set to send method
 
  if (method=="POST"){                         // If POST 
    while (!WScript.StdIn.AtEndOfStream){      // Read data from stdin
     data_str += WScript.StdIn.ReadAll();      // Build string
    }                                          // Loop until no more data
  }
  else{                                        // Method was GET
    data_str = objEnv("QUERY_STRING");         // Set data to query string
  }
 
 if (data_str ==""){                            //If string empty
   return cgi_hash;                             //Return the blank array
 }

  // Split and save all variable-value pairs to array
  var variable_array = data_str.split ("&");  

  for (i=0;i<variable_array.length;i++){      // Scan array
    var pair_str = variable_array[i];         // Get variable-value pairs
    var cgi_variables = pair_str.split("=");  // Split into variable/value

    var decoded = cgi_variables[1];           // Get encoded value
    decoded = decoded.replace(/\+/gi, " ");   // Replace special character +
    decoded = unescape(decoded);              // Complete the decoding

    cgi_hash[cgi_variables[0]] = decoded;     // Add to associative array 
  }                                           // index set to variable  
  return cgi_hash;                            //Return the array
} //End function
//========================================== End Function Get CGI variables ===

An example of its use is shown on the right:

  // Example of function use:
  var cgi_vars = new Array;       // Create new array
  cgi_vars     = cgi_variables(); // Get CGI variables
     //Use square index brackets 
  WSH.Echo("Text value: " + cgi_vars["text"]     );
  WSH.Echo("Language: "   + cgi_vars["Language"] );
    //Or use the dot operator
  WSH.Echo("Text value: " + cgi_vars.text        );
  WSH.Echo("Language: "   + cgi_vars.Language    );

Top

Summary

The Get CGI variables function is similar in both VBScript and JavaScript this is an important function when writing any CGI script. At this stage you currently have enough information to creative dynamic web pages written in either VBScript or Jscript.

Remainder of this tutorial concentrates on writing CGI scripts using VBScript. You will quickly find a need for storing data this can be in the form of a database such as a MySQL server alternatively a file-based system. A file based database is coved on the next two pages this is suitable for the majority of simple application.

Where to next

Next page covers the VBScript Dictionary this will be used as the main component for a file-based database.


Top