Introduction to CGI Scripting

To turn this program into a CGI script, we need to rename it and make it print out HTML. Here are the contents of the new file, hello.cgi:


use strict;

use warnings;


print "Content-type: text/html\n\n";

print "<html>\n";

print "<head>\n";

print "<title>Greetings</title>\n";

print "</head>\n";

print "<body bgcolor=\"red\"><center>\n";

print "<H1>Hello Dean!</H1>\n";

print "</body>\n";

print "</html>\n";


Note that the first 'print' statement tells the browser that it is receiving HTML content. This is required from all CGI scripts. Also note that when I needed to print out double-quotes around the "red" in bgcolor="red", I prefixed them with a forward-slash ('\').

When you finish writing this content then save the file and exit emacs, make the script 'executable', and then run it to test it:

ubuntu@ubuntu:~$ emacs -nw hello.cgi

ubuntu@ubuntu:~$ chmod u+x hello.cgi

ubuntu@ubuntu:~$ ./hello.cgi

Content-type: text/html






<body bgcolor="red"><center>

<H1>Hello Dean!</H1>





Alright, we have our first CGI script! Let's install it and try it out.

First, we need to create the /var/www/cgi-bin directory, because that is where we configured the apache2 web server to look for CGI scripts.

ubuntu@ubuntu:~$ sudo mkdir /var/www/cgi-bin



Next, we need to copy the script to this location:

ubuntu@ubuntu:~$ sudo cp hello.cgi /var/www/cgi-bin/



Finally, since the apache web server will need permission to execute this file, we need to give 'all users' permission to execute it:

ubuntu@ubuntu:~$ sudo chmod a+x /var/www/cgi-bin/hello.cgi



Now bring up your browser and append /cgi-bin/hello.cgi to the IP address of the Raspberry Pi. What do you see?

Note that if you run into any errors, the apache2 logs are stored in the /var/log/apache2/ directory. The /var/log/apache2/error.log file will contain any errors with executing CGI scripts.