Create a Web Page that Counts

Now that we know how to provide input to a CGI script, we can create a feedback loop for our first interactive web page. We will do this by adding URL links to the web page that point back to the CGI script and include new information based on user input.

Let's create a simple 'counter' page that displays a number starting at '0' and lets the user increment or decrement this number, and the web page will keep track of the user input and display the current number. What would this code look like?

Let's break down the steps:

- number starts at 0;

- if CGI script is given a different number, set number to this input;

- display number;

- make 'increment' link to CGI script to pass current number + 1;

- make 'decrement' link to CGI script to pass current number - 1;

 

Here is one way to create this CGI script:

ubuntu@ubuntu:~$ cat counter.cgi

#!/usr/bin/perl

use strict;

use warnings;

 

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

print "<html>\n";

print "<head>\n";

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

print "</head>\n";

print "<body>\n";

my $count = 0;

if (exists $ENV{'QUERY_STRING'}) {

 

    my $qstr = $ENV{'QUERY_STRING'};

    my @settings = split /&/, $qstr;

 

    foreach my $s (@settings) {

        my @items = split /=/, $s;

        next unless (@items == 2);

        if ("$items[0]" eq "count") {

            $count = $items[1];

        }

    }

}

 

my $up = $count + 1;

my $down = $count - 1;

print "<center>\n";

print "<A HREF=\"counter.cgi?count=$up\"><H2>Increment</H2></A>\n";

print "<H1>$count</H1>\n";

print "<A HREF=\"counter.cgi?count=$down\"><H2>Decrement</H2></A>\n";

print "</center>\n";

print "</body>\n";

print "</html>\n";

 

This CGI script initializes a $count variable to '0'. Then it looks in the QUERY_STRING setting to see if a 'count' variable exists, and if so then it sets the $count variable to that number.

Then it calculates the new incremental value ($up) and new decremental value ($down).

Then it prints the 'Increment' web link, then the number, and finally the 'Decrement' web link.

When you finish writing your version, make it executable and run it to test it for errors:

ubuntu@ubuntu:~$ chmod a+x counter.cgi

ubuntu@ubuntu:~$ ./counter.cgi

Content-type: text/html

<html>

<head>

<title>Counter</title>

</head>

<body>

<center>

<A HREF="counter.cgi?count=1"><H2>Increment</H2></A>

<H1>0</H1>

<A HREF="counter.cgi?count=-1"><H2>Decrement</H2></A>

</center>

</body>

</html>

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

ubuntu@ubuntu:~$

 

If it looks good then copy it to the /var/www/cgi-bin/ directory and append /cgi-bin/counter.cgi to your Raspberry Pi IP address in your browser URL window. Does it work?

Copyright 2020
  • Facebook - Black Circle
  • Twitter - Black Circle
  • YouTube - Black Circle
  • Instagram - Black Circle
Follow us on these platforms