CGI Request Handling

When a web server receives a request for a dynamic page, it can pass the work to a separate program instead of returning a stored file. The Common Gateway Interface (CGI) is the agreement behind that hand-off. The server describes the request in environment variables and delivers any request body on standard input. Whatever the program writes to standard output goes back to the client. CGI uses only process-level tools you already know from C, such as getenv, stdin and stdout, so it shows plainly how an HTTP request becomes an ordinary process with inputs and outputs.

How the server describes a request

For each request, the server starts a new process for the program and fills that process's environment before the program runs. The request details are not passed as function arguments; your main reads them with getenv. The variables below are the ones you will use most.


Variable

Holds

Example value

REQUEST_METHOD

The HTTP method of the request

POST

QUERY_STRING

Everything after the ? in the URL, still encoded

id=42&sort=asc

CONTENT_LENGTH

Size of the request body in bytes

27

CONTENT_TYPE

Media type of the request body

application/x-www-form-urlencoded

PATH_INFO

Extra path text after the script name

/reports/2026

REMOTE_ADDR

Network address of the client

203.0.113.7


A variable that does not apply to a request may be missing entirely, so getenv can return NULL. Check the pointer before you use it.


Flow diagram showing a browser sending an HTTP request to a web server, which passes environment variables and the request body on standard input to a CGI program and receives the response on standard output.


Reading GET and POST data

A form sent with GET puts its fields in the URL, so the program reads them from QUERY_STRING and there is no body. A form sent with POST puts its fields in the request body. The server writes the body to the program's standard input and sets CONTENT_LENGTH to its size, so the program must read exactly that many bytes from stdin.


Either way, ordinary form data arrives in URL encoding: name=value pairs joined by &, a space written as +, and any reserved or non-ASCII byte written as % followed by two hexadecimal digits. Each escape uses three characters for one byte, while + to space is one-for-one, so the length of a decoded value follows directly:


Ldecoded=Lencoded−2EL_{\text{decoded}} = L_{\text{encoded}} - 2E


Here EE is the number of %XX escapes. Example: the value 5%25+tax has 8 encoded characters and one escape, so it decodes to the 6-byte string 5% tax. A C buffer for it needs 7 bytes, including the terminating '\0'.



Writing the response

The program answers by printing to standard output. First come one or more header lines, then a blank line that ends the headers, then the body. A normal page needs a Content-Type header. A Status header such as Status: 404 Not Found changes the HTTP status, and a Location header requests a redirect. The server adds the HTTP status line and any remaining headers before forwarding the reply. The snippet below assumes the standard headers stdio.h and stdlib.h are included. It answers a negative CONTENT_LENGTH with 400 Bad Request and a body too big for its buffer with 413 Payload Too Large.


C
int main(void) {
    const char *len_str = getenv("CONTENT_LENGTH");
    long len = len_str ? strtol(len_str, NULL, 10) : 0;
    char body[1024];

    if (len < 0) {
        printf("Status: 400 Bad Request\r\n");
        printf("Content-Type: text/plain\r\n\r\n");
        printf("Invalid Content-Length.\n");
        return 0;
    }
    if (len >= (long)sizeof body) {
        printf("Status: 413 Payload Too Large\r\n");
        printf("Content-Type: text/plain\r\n\r\n");
        printf("Request body too large.\n");
        return 0;
    }
    size_t got = fread(body, 1, (size_t)len, stdin);
    body[got] = '\0';

    printf("Content-Type: text/plain\r\n\r\n");
    printf("Received %zu bytes.\n", got);
    return 0;
}



What to remember

  • The server passes request details in environment variables; read them with getenv and handle NULL.
  • GET data is in QUERY_STRING; POST data is on stdin, exactly CONTENT_LENGTH bytes long and still encoded.
  • Decode + to a space and each %XX to one byte, so Ldecoded=Lencoded−2EL_{\text{decoded}} = L_{\text{encoded}} - 2E.
  • Print headers, a blank line, then the body.

Example: Handling a POST Order Form in C

An order page submits a form with method POST to the script URL /cgi-bin/order, which has no query string. The browser transmits this request body:


item=USB+cable&note=50%25+off&qty=2


Your C program must read the body, recover the note the customer typed, and reply with a plain-text confirmation.


a) Give the values the server places in REQUEST_METHOD, QUERY_STRING and CONTENT_LENGTH.


The form was submitted with POST, so REQUEST_METHOD is POST. The action URL contains no ?, so the server defines QUERY_STRING as the empty string.


CONTENT_LENGTH counts the bytes of the body exactly as transmitted, still encoded. Split the body at the separators: item=USB+cable has ________ characters, note=50%25+off has ________ characters, qty=2 has ________ characters, and the two & separators add ________ more.


14+14+5+2=3514 + 14 + 5 + 2 = 35


The server sets CONTENT_LENGTH to 35 bytes.


b) Decode the note value and find the smallest char array that can hold it as a C string.


The encoded value is 50%25+off, which is 9 characters long. Hexadecimal 25 is decimal 37, the ASCII code for ________, so %25 becomes one byte. The + stands for a ________. The decoded text is 50% off.


The value contains ________ percent escape, so its decoded length is ________ bytes:


Ldecoded=Lencoded−2E=9−2(1)=7L_{\text{decoded}} = L_{\text{encoded}} - 2E = 9 - 2(1) = 7


A C string also needs the terminating '\0', so the smallest array is char note[8], which is 8 bytes.


c) Describe the code in main that reads the body and sends a valid response, and state how many bytes fread should request.


fread should request exactly CONTENT_LENGTH bytes, which is 35 here. Asking for more, or looping until end of file, can block, because the server need not signal end of file after the body. The steps are:

  1. Read the length: const char *s = getenv("CONTENT_LENGTH"); then long len = s ? strtol(s, NULL, 10) : 0; so a missing variable counts as zero.
  2. Check it against the buffer, leaving one byte for the terminator: with char body[512];, reject len < 0 || len >= (long)sizeof body. A negative value is invalid. Print an error response with Status: 400 Bad Request for a negative length or Status: 413 Payload Too Large for an oversized body, followed by a Content-Type header and a blank line, then return without calling fread.
  3. Read and terminate: size_t got = fread(body, 1, (size_t)len, stdin); then body[got] = '\0'; so the 35 bytes become a C string.
  4. Reply: printf("Content-Type: text/plain\r\n\r\n"); prints the header and the blank line that ends the headers, and printf("Order received: %zu bytes.\n", got); prints the body.

For this request the program reads 35 bytes, and the client sees the plain-text line Order received: 35 bytes.

Match each CGI environment variable that a web server sets for an incoming request with a description of the information it carries for the program.

Match each term
A.

The network address of the client that sent the request

B.

Extra path segments that follow the script name in the URL

C.

How many bytes of request body are waiting on standard input

D.

The media type of the request body, such as application/x-www-form-urlencoded

E.

The HTTP verb the client used, such as GET or POST

F.

The still-encoded text after the question mark in the requested URL

CONTENT_TYPE

QUERY_STRING

REQUEST_METHOD

CONTENT_LENGTH

PATH_INFO

REMOTE_ADDR

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A registration form is submitted with method POST. The browser sends this request body to the CGI script exactly as shown:


city=St.+John%27s&zip=A1B


What value does the web server place in the CONTENT_LENGTH environment variable? Give your answer in bytes as a whole number.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A C program run through the CGI writes its entire response to standard output. It starts with header lines that the web server reads before it builds the HTTP reply. Fill in each blank with a header name or a three-digit status code.


The header that tells the browser how to interpret the body, for example as text/html, is . To report a missing record, the program prints a header with the value 404 Not Found. To send the browser to a different absolute URL, the program prints a header and no other header, and the server then answers the client with status code . When the program prints a document with no Status header at all, the server sends status code .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice