Tuesday, 21 May 2013

CGI-bin - and batch files!

I had a little play with Windows Batch Files and CGI after spotting a question on StackOverflow and trying to help.

Having installed WampServer for experiments with PHP and MVC frameworks like Yii and Laravel, it was easy to add a test batch file in the www folder and try some things out. Building upon something I found at http://www.jlk.net/apache/testing_cgi.shtml .... I wrapped it up into HTML and sorted out the Parameters Count (ArgC)  :

@echo off
  rem  This works in Wampserver's Apache cgi-bin...
  rem     http://localhost/cgi-bin/testbat.bat?param1+param2
echo Content-Type: text/html
echo.
echo ^<html^>^<head^>^</head^>^<body^>
echo ^<H1^>Hello world!!!^</H1^>

echo ^<PRE^>
echo argV = %0

set argC=0
for %%x in (%*) do Set /A argC+=1
echo argC = %argC%

echo %%1 = %1
echo %%2 = %2
echo %%3 = %3
echo.

echo SERVER_SOFTWARE = %SERVER_SOFTWARE%
echo SERVER_NAME = %SERVER_NAME%
echo GATEWAY_INTERFACE = %GATEWAY_INTERFACE%
echo SERVER_PROTOCOL = %SERVER_PROTOCOL%
echo SERVER_PORT = %SERVER_PORT%
echo REQUEST_METHOD = %REQUEST_METHOD%
echo HTTP_ACCEPT = "%HTTP_ACCEPT%"
echo PATH_INFO = "%PATH_INFO%"
echo PATH_TRANSLATED = "%PATH_TRANSLATED%"
echo SCRIPT_NAME = "%SCRIPT_NAME%"
echo QUERY_STRING = "%QUERY_STRING%"
echo REMOTE_HOST = %REMOTE_HOST%
echo REMOTE_ADDR = %REMOTE_ADDR%
echo REMOTE_USER = %REMOTE_USER%
echo AUTH_TYPE = %AUTH_TYPE%
echo CONTENT_TYPE = %CONTENT_TYPE%
echo CONTENT_LENGTH = %CONTENT_LENGTH%
echo ^</PRE^>

echo ^</body^>^</html^>
Given that batch files are a lot more capable than they used to be back in the 80s, it's intriguing to ponder just how much you could achieve this way!

Back to the StackOverflow question, it seems that some commands that work individually at the command prompt don't actually seem to work in a CGI batch file. I found that it may be possible to get around this with a 'FOR' construct to execute a command somewhat indirectly  :
FOR /F "usebackq delims==" %%x IN (`cmd /c echo NOT hidden from browser`) do echo %%x

All good fun. Please let me know if you find this useful :)

No comments:

Post a Comment