CGI - Displaying data in a browser

March 2017

The purpose of a CGI scripta

CGI scripts are designed to display webpages generated by a computer program (dynamic web pages). However, given that the server sends data generated by the CGI script to the browser, in its "raw" form. It is necessary to add the HTTP headers in order for the browser to understand that this is a webpage.

The CGI program must then create these HTTP headers.

Sending HTTP headers

Since the server does not create the headers, the CGI script must start by sending an HTTP header for the type of file it is sending. Given that the main role of CGI is to create dynamic pages, the HTTP header the most commonly used will be in html/text type. The first string to be sent to the browser is as follows:

content-type : text/html\n\n

The two line breaks are essential!
  • The first is required to move to the next line;
  • The second is used to create the blank line separating the HTTP headers of the message body, as specified by the HTTP protocol.

Example CGI script written in Perl

An example of a simple script to display a web page that says "Hello World":

#! /usr/local/bin/perl
print "content-type : text/html\n\n";

print "<HTML>";

print "<HEAD>";

print "<TITLE>Hello world</TITLE>";

print "</HEAD>";

print "<BODY>";

print "Hello world!";

print "</BODY>";

print "</HTML>";

Now in this example the CGI program performs a redirect to following URL

#! /usr/local/bin/perl
print "location :";

Orignal document published on


Published by deri58.
This document, titled "CGI - Displaying data in a browser," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (