Can I write CGI scripts in Visual Basic?
Contributors:
- MichaelGiordano cissmjg@hotmail.com
The answer is YES! You must use either VB4/32, VB5 or VB6. The secret lies in using 3 Win32 API calls :
- GetStdHandle
- ReadFile
- WriteFile
For convenience you might want to declare the following constants :
Private Const STD_INPUT_HANDLE = -10& Private Const STD_OUTPUT_HANDLE = -11&
Sending output data to the web server is pretty easy so we'll cover that first. Assuming lResult is a long and that the variable sOutput is a String containing information to be displayed, simply call WriteFile as follows :
WriteFile GetStdHandle(STD_OUTPUT_HANDLE), _
sOutput, _
Len(sOutput), _
lResult, _
ByVal 0&
Getting data from the web server is only slightly trickier. There are two cases METHOD=GET and METHOD=POST. We'll cover METHOD=GET first.
By using the Environ$ function and looping through the environment, the QUERY_STRING environment variable will contain the web server data.
Dim iEnvItem as Integer, iOffset as Integer
Dim sWork as String, sEnvVar as String
Dim sQS as String
iEnvItem = 0
Do
sWork = Environ$(iEnvItem + 1)
iOffset = InStr(sWork, "=")
sEnvVar = UCase(Left(sWork, iOffset - 1))
If sEnvVar = "QUERY_STRING" Then
sQS = Mid(sWork, iOffset + 1)
Exit Do
End If
iEnvItem = iEnvItem + 1
Loop
Getting data via METHOD=POST requires a call to ReadFile. Below is a sample code snippet:
'Note that mvarCONTENT_LENGTH contains the CONTENT_LENGTH environment variable.
Dim lpszBuf as String
Dim lBytesRead as Long
lpszBuf = String$(mvarCONTENT_LENGTH + 1, 0)
lBytesRead = mvarCONTENT_LENGTH
lResult = ReadFile(GetStdHandle(STD_INPUT_HANDLE), _
ByVal lpszBuf, _
mvarCONTENT_LENGTH, _
lBytesRead, _
ByVal 0&)
A complete VB project (inspired by Chapter 20 of the book CGI by Example by Robert Niles and Jeffry Dwight ISBN: 0-7897-0877-9) is available here.
The project also contains a sample program (Cgitst.vbp) that when compiled and placed in the appropriate cgi-bin type directory will display all CGI variables for an HTML form.
Previous | Next | Table of Contents
Follow us on Twitter | Contact Us
Copyright 1994-2012 Boutell.Com, Inc. All Rights Reserved.