Processing GET and POST requests in CGI with C

On the client side, the form submission method (GET or POST) is specified in the attribute method of the form element.

Form that uses the GET method

<form method="get" action="...">

Enter your name:

Form that uses the POST method

<form method="post" action="...">

Enter your name:


On the server side, the difference between the processing of the GET request and the POST request is that in the first case the parameters string is set as an environmental variable QUERY_STRING, while in the second case the parameter string is put on the standard input stream. In our example, both methods are handled by the following C code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  char *param = calloc(101, 1);              // storage for param string
  if (! param) return(1); 
  char *param_str;                           // copy of parameter string
  if (param_str = getenv("QUERY_STRING"))
    strncpy(param, param_str, 100);          // get params with GET
  char *method = "GET";

  if (! param || strlen(param)<2)            // get parameters with POST
  {
    fgets(param, 100, stdin);
    method = "POST";
  }

  param_str = malloc(strlen(param)+1);       // copy the original param string
  strcpy(param_str, param);

  char *name = strtok(param, "=");           // get parameter name
  char *value = strtok(NULL, "=");           // get parameter value 

  printf("Content-Type: text/html\n\n");     // compose the returned HTML 
  printf("<html><head><title></title></head><body>");
  printf("Method: %s <br>", method);
  printf("Parameter string: %s <br>", param_str);
  printf("Parameter name: %s <br>", name);
  printf("Parameter value: %s <br>", value);
  printf("</body></html>");
  return(0);
}

Note that this simple script does not accept parameter strings exceeding 100 characters and does not do URI decoding.

Check here to see how this task can be established with Java.