Thursday, March 6, 2014

CGI - Common Gateway Interface

What is the first thing come to your mind, when you see... CGI? Me -- Perl. But it's actually more than Perl. Here's some examples on CGI in different languages and some setups on Ubuntu to get the web server running.

To setup Apache2 in Ubuntu. This will install and run the Apache2 server :

sudo apt-get install apache2

By default, the cgi directory is setup at /usr/lib/cgi-bin. Just have your cgi scripts or executable put in this directory (make sure it's executable) and it can be access via http://localhost/cgi-bin/path. This can be modified at the config file. The default config file is at /etc/apache2/sites-available/default. The section of the file that related to this looked like this :

 
 ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
 <Directory "/usr/lib/cgi-bin">
  AllowOverride None
  Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
  Order allow,deny
  Allow from all
 </Directory>


The access and error log can be found at /var/log/apache2/.

OK, now begin the example on cgi scripts/executable.

Let's start with Perl.

#!/usr/bin/perl

use CGI;

$cgi = new CGI();
print $cgi->header();
print "<b>Hello!</b>\n";


Perl has a CGI library, which you can use it to print the required header before your content to make it as a valid/recognizable header for the web server to process. Without the CGI library, the code can be as below.

#!/usr/bin/perl

print "Content-type: text/html\n\n";
print "<b>Hello!</b>\n";


"Content-type: text/html\n\n" is expected header for html document, and if it's a text document, the html can be replaced with plain.

I heard of C/C++ can be programmed for web application, but I never know how or I didn't bother to Google it. And I found out, actually it's also a form of CGI, so now I know CGI != Perl. :)

For C code :

#include <stdio.h>
int main(void) {
  printf("Content-Type: text/html\n\n");
  printf("<b>Hello</b>\n");
  return 0;
}

For C code, it needs to be compiled. You can try cc or gcc to compile it. Example :

cc -o hello.cgi hello.c

Now, let's go for shell scripts!

#!/bin/bash
echo "Content-type: text/html"
echo ""
echo "<b>Hello</b>\n"

All of these scripts are giving the same result. Make sure they all are executable. :)


References :
https://www.cs.tut.fi/~jkorpela/forms/cgic.html
http://help.cs.umn.edu/web/cgi-tutorial

No comments:

Post a Comment