Skip to main content

CGI script execution mechanism

Short answer

The web server recognizes a CGI URL, forks a new process for the script, passes request data through environment variables and stdin for POST, and the script writes headers and HTML to stdout, which the server sends back. One process per request makes CGI slow.

Explain the CGI server side script execution mechanism.

CGI (Common Gateway Interface) is a standard that defines how a web server passes a request to an external program (CGI script, written in Perl, C, Python, shell, etc.), and how the program returns its output to the server so that dynamic pages can be created.

Execution mechanism

  1. The browser sends an HTTP request for a CGI URL, e.g. http://site.com/cgi-bin/search.pl?q=web.
  2. The web server recognises, from the URL or directory (/cgi-bin/), that this is a program, not a static file.
  3. The server creates a new process and starts the script.
  4. Request information is passed through environment variables (REQUEST_METHOD, QUERY_STRING, CONTENT_LENGTH, REMOTE_ADDR, HTTP_USER_AGENT). For POST, the form data is passed through standard input (stdin).
  5. The script processes the data, possibly querying a database or files.
  6. The script writes to standard output (stdout) a header (e.g. Content-type: text/html), a blank line, then the HTML body.
  7. The server reads this output, adds HTTP headers (status line) and sends the response to the browser.
  8. The CGI process terminates.
Browser --HTTP request--> Web server
                            | fork new process
                            | env vars + stdin
                            v
                       CGI script --> (DB / files)
                            | stdout (headers + HTML)
                            v
Browser <--HTTP response-- Web server

Example (Perl)

#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<html><body><h1>Hello from CGI</h1></body></html>";

Disadvantages

A new process per request is slow and uses memory, which does not scale well. Improved alternatives: FastCGI, mod_perl, servlets and PHP modules.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Web Technology chapter 3 questions →