Page 1 of 1

RunProgram + CGI

Posted: Thu Sep 05, 2024 12:29 pm
by the.weavster
PB[C] on MX Linux x86_64

Why doesn't the below work?

First a simple CGI (compile as test.cgi)

Code: Select all

EnableExplicit

If Not InitCGI()
  End
EndIf

Define.i nBufferSize = ReadCGI()
Define.s sBody = PeekS(CGIBuffer(), nBufferSize, #PB_UTF8)
Define.s sResponse = "Hello, " + sBody

WriteCGIHeader(#PB_CGI_HeaderContentType, "text/plain")
WriteCGIHeader(#PB_CGI_HeaderContentLength, Str(StringByteLength(sResponse, #PB_UTF8)), #PB_CGI_LastHeader)
WriteCGIString(sResponse)
Now try to run test.cgi and pass in some text:

Code: Select all

EnableExplicit

Procedure.s TestCGI(sProgram.s, sBody.s)
  Define.s sOutput = ""
  Define.i nPrg = RunProgram(sProgram, "", GetCurrentDirectory(), #PB_Program_Open|#PB_Program_Hide|#PB_Program_Read|#PB_Program_Write)
  If nPrg
    WriteProgramString(nPrg, sBody, #PB_UTF8)
    While ProgramRunning(nPrg)
      Define.i nRes = AvailableProgramOutput(nPrg)
      If nRes > 0
        sOutput + ReadProgramString(nPrg, #PB_UTF8) + #CRLF$
      EndIf
    Wend
    CloseProgram(nPrg)
  Else
    sOutput = "Could not run " + sProgram
  EndIf  
  ProcedureReturn sOutput
EndProcedure

Debug TestCGI(#PB_Compiler_FilePath + "test.cgi", "World!")
The text I'm trying to pass in ( i.e. World! ) doesn't get read.

Re: RunProgram + CGI

Posted: Thu Sep 05, 2024 4:26 pm
by the.weavster
I got it, I had to set some environment variables first:

Code: Select all

EnableExplicit

Procedure.s TestCGI(sProgram.s, sBody.s, sParam.s="")
  Define.s sOutput = ""
  Define.i nSize = StringByteLength(sBody, #PB_UTF8)
  SetEnvironmentVariable(#PB_CGI_ContentLength, Str(nSize))
  SetEnvironmentVariable(#PB_CGI_RequestMethod, "POST")
  
  Define.i nPrg = RunProgram(sProgram, sParam, "", #PB_Program_Open|#PB_Program_Hide|#PB_Program_Read|#PB_Program_Write)
  If nPrg
    Define *bfr = UTF8(sBody)
    WriteProgramData(nPrg, *bfr, nSize)
    WriteProgramData(nPrg, #PB_Program_Eof, 0)
    While ProgramRunning(nPrg)
      Define.i nRes = AvailableProgramOutput(nPrg)
      If nRes > 0
        sOutput + ReadProgramString(nPrg, #PB_UTF8) + #CRLF$
      EndIf
    Wend
    CloseProgram(nPrg)
    FreeMemory(*bfr)
  Else
    sOutput = "Could not run " + sProgram
  EndIf
  ProcedureReturn sOutput
EndProcedure

Debug TestCGI(#PB_Compiler_FilePath + "test.cgi", "World!")