CGI Programming, Getting User Input

The GET and POST methods

GET
User input passed through environmental variable QUERY_STRING or PATH_INFO if Extra Path Information method used
Can access CGI application with a HTML form
Browser or server may truncate data
POST
Read CONTENT_LENGTH bytes of user input from STDIN
Need HTML form to post data
No size limit on query string

Encoding Query Strings

'Encode' in Perl

#!/usr/local/bin/perl

print "Enter string to encode:\n";
chop( $str = <STDIN> );

$str =~ s/(\W)/sprintf( "%%%x", ord($1) )/eg;

print "\nEncoded string:\n\n";
print "$str\n";

exit 0;

Try these...

http://localhost:8080/cgi-bin/env?arg1=Matthew%20Feldt&arg2=Internet%20Developer
http://localhost:8080/cgi-bin/env/arg1/arg2/arg3

You'll notice http://localhost:8080/cgi-bin/env/arg1/arg2/arg3 creates some new variables

    PATH_INFO = /arg1/arg2/arg3
    PATH_TRANSLATED = /tmp/web/htdocs/arg1/arg2/arg3

This is an example of the Extra Path Information method


Decoding Query Strings

Code fragment from cgi-lib.pl in Perl

sub MethGet {
  return ($ENV{'REQUEST_METHOD'} eq "GET");
}

sub ReadParse {
  local (*in) = @_ if @_;
  local ($i, $key, $val);

  # Read in text
  if (&MethGet) {
    $in = $ENV{'QUERY_STRING'};
  } elsif ($ENV{'REQUEST_METHOD'} eq "POST") {
    read(STDIN,$in,$ENV{'CONTENT_LENGTH'});
  }

  @in = split(/&/,$in);

  foreach $i (0 .. $#in) {
    # Convert plus's to spaces
    $in[$i] =~ s/\+/ /g;

    # Split into key and value.  
    ($key, $val) = split(/=/,$in[$i],2); # splits on the first =.

    # Convert %XX from hex numbers to alphanumeric
    $key =~ s/%(..)/pack("c",hex($1))/ge;
    $val =~ s/%(..)/pack("c",hex($1))/ge;

    # Associate key and value
    $in{$key} .= "\0" if (defined($in{$key})); # \0 is the multiple separator
    $in{$key} .= $val;

  }

  return length($in); 
}

Similar C code is available from NCSA's util.c, post-query.c, query.c source

Something Useful


Last Modified: 17 February 1997

St. Louis Unix Users Group - Linux SIG