7. How a CGI Applications Work? CGI Application User Web Browser 1 2 3 4 HTTP Request HTTP Response CGI Program’s Response Call CGI Server Application (on Server)
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22. Example: Count Click Script #!/usr/bin/perl # ######################### ## Author: Sopan Shewale ### This script is created for giving demo on click count. ## The Script is support to display increse/decrease click's, handles back button of browser, does not handle reload stuff. ## also it's based on sessions. ######################## use strict; use warnings; use CGI; use CGI::Session; use CGI::Cookie; my $q = new CGI(); my $sessionid = $q->cookie("CGISESSID") || undef; my $session = new CGI::Session(undef, $sessionid, {Directory=>'/tmp'}); $sessionid = $session->id(); my $cookie = new CGI::Cookie(-name=>'CGISESSID', -value=>$sessionid, -path=>"/"); print $q->header('text/html', -cookie=>$cookie); print $q->start_html("Welcome to Click Count Demo"); print "<h1>Welcome to Click Count Demo</h1>"; my $count = $session->param('count'); ## count-is click count variable if(!defined($count)) { $session->param('count', 0); $count=0;} ### if session is first time created, set count=0 $session->param('count', $count); $count = $session->param('count'); #print "<h1>The Click Count is: $count "; ## Form stuff print $q->startform(-method=>'POST'); print $q->submit( -name=>"Increase", -value=>'Increase1'); print $q->submit( -name=>"Decrease", -value=>'Decrease1'); print $q->endform();
23. Example: Count Click Script (Cont…) ## Which button is being pressed my $which_button = $q->param('Increase'); if(defined ($which_button)) { print "Increase pressed"; $count = increase_count($count); ## Increase the count since increase button is clicked $session->param('count', $count); }else { $which_button=$q->param('Decrease'); if(defined($which_button)){ print "Decrease pressed"; $count = decrease_count($count); ## Decrease the count since decrease button is clicked $session->param('count', $count); } else {print "You have not pressed any button, seems you are typing/re-typing the same URL"; } } $count = $session->param('count'); print "<h1>The Click Count is: $count "; print $q->end_html(); ## increases the count by 1 sub increase_count { my $number = shift; $number = $number +1; return $number; } ## decreases the count by 1 sub decrease_count { my $number = shift; $number = $number -1; return $number; }