How to implement CGI in a Web Server

I am trying to write a small HTTP server using Java. I have some doubt
about how to implement CGI.

This is a portion of Java code that handles HTTP POST method, and
tries to execute a PHP script. I feel this is the correct way to
implement CGI (of course there are many more environment variables
which I must set for CGI, which I'll do later). Later I'll try to
incorporate CGI programs written in any CGI programming language.

String[] cmdarray = {"C:\\php-5.0.5\\php.exe", "htdocs\\test.php"};
String[] envp = {"CONTENT_LENGTH="+clength,
"CONTENT_TYPE=application/x-www-form-urlencoded"};

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmdarray, envp);
InputStream pis = process.getInputStream();

String header = "HTTP/1.1 200 OK\n";
header += "Content-Type: text/html\n\n";

os.write(header.getBytes());
os.flush();

int n = 0;
while ((n = pis.read()) != -1) {
  char c = (char)n;
  os.write(c);
  os.flush();
}

I am correctly assigning the value to variable clength for
CONTENT_LENGTH environment variable (taken from request header
Content-Length). os is the OutputStream attached to the socket which
is bound to a specific connection from the browser.

The PHP script (test.php) gets correctly called, and the output from
PHP script correctly gets displayed on the browser. But the problem
happens when I submit a HTML form to be handled by PHP. How will the
PHP script read form data from HTTP body in the request? For
information I must tell that HTML form POST data is accessible in the
PHP script as $_POST["name"] (which presently incorrectly sets to
null).

I'll be grateful for any pointers to solve this problem, and also any
comments on the CGI implementation approach I am using..

Regards,
Mukul

Received on Wednesday, 3 May 2006 15:32:46 UTC