CGI - Displaying data in a browser

December 2016



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
http://www.commentcamarche.net.

#! /usr/local/bin/perl
print "location : http://www.commentcamarche.net";


Orignal document published on CommentCaMarche.net.

Related :

This document entitled « CGI - Displaying data in a browser » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.