Tuesday, October 21, 2014

CGI scripting in Perl

In simple term CGI scripting in Perl denotes posting/ passing of values via get/ post method ( e.g: from a html form ) to a server side Perl script, which in turn accepts those values for further processing.

#!/usr/bin/perl

use CGI; # required for CGI programming

print "content-type:text/html\n\n"; # defining output type header

my $q = new CGI; # creating a CGI object, required here for accepting the values passed to the script

my $submit_value = $q->param('submit'); # accepting value of the submit button passed to the script on form submission

if ($submit_value eq '') {
 &form(); # if submit button is not clicked, a call is made to this subroutine to display the html form 
}
else
{
 &show(); # if submit button is clicked, a call is made to this subroutine to process the values passed from the html form 
}

sub form 
{
 # following displays the html form in the web browser
 print qq{
  
   
    My First CGI Script
   
   
    
Enter Your Name :

Enter Your Age :

Enter Your Address :

}; } sub show { # following accepts values of the text boxes present in the html form and passed to the script on form submission my $my_name_value = $q->param('my_name'); my $my_age_value = $q->param('my_age'); my $my_addr_value = $q->param('my_addr'); # following displays a html output, using the values passed to the script on form submission print qq{ Hello!!! My name is $my_name_value

I am $my_age_value years old

I live in $my_addr_value

Back }; }

Output:
-------
Considering the above script filename to be 'test_cgi.pl' present inside the location '/var/www/cgi-bin/test/' of the web server, to checkout the file uploading functionality, please call the above script in the following format from a web browser:

http://server_address/cgi-bin/test/test_cgi.pl

Now input your name, age, address in the text boxes provided, then click on submit and see the magic!!!