On Tue, Mar 26, 2002 at 05:08:04PM +0000, Ian Stuart wrote:
>
> OK, I now have a system that works as a simple CGI script:
> http://lucas.ucs.ed.ac.uk/cgi-bin/gallery.cgi
>
> I am now attempting to move to a sessional system, and have some code
> that works mostly fine, based on Philips origional code.
>
> The problem I now have is reading the parameters that are passed back to
> the server.
>
> The code snippit I'm using is:
> # find session ID in $req, put in $sessionID
> my @params = split /&/, $req->content;
> my %param;
> foreach $item (@params) {
> my ($key, $value) = split /=/, $item;
> $param{$key} = $value;
> }
> my $sessionID = $param{'sessionID'};
> however this seems to work intermittently.
>
> Can someone offer a better solution?
[...]
These functions have served me well in minor projects. You may also
want to look at POE::Component::Server::HTTP. I'm not sure it does
URL decoding, but it may simplify your project overall.
-- Rocco Caputo / [EMAIL PROTECTED] / poe.perl.org / poe.sf.net
#------------------------------------------------------------------------------
# Build two URL-encoding maps. Map non-printable characters to
# hexified ordinal values, and map hexified ordinal values back to
# non-printable characters.
my (%raw_to_url, %url_to_raw);
# Nonprintable characters
for my $ord (0..255) {
my $character = chr($ord);
my $hex = lc(unpack('H2', $character));
# Map characters to their hex values, including the escape.
$raw_to_url{ $character } = '%' . $hex;
# Map hex codes (lower- and uppercase) to characters. Doesn't
# handle mixed-case hex.
$url_to_raw{ $hex } = $character;
$url_to_raw{ uc $hex } = $character;
}
# Decode url-encoded data. This code is adapted from Lincoln Stein's
# CGI.pm module, but it avoids eval (s///e).
sub url_decode {
my $data = shift;
return undef unless defined $data;
$data =~ tr[+][ ];
$data =~ s/%([0-9a-fA-F]{2})/$url_to_raw{$1}/g;
return $data;
}
# Url-encode things. Also adapted from Lincoln Stein's CGI.pm.
sub url_encode {
my $data = shift;
return undef unless defined $data;
$data =~ s/([^a-zA-Z0-9_.:=\&\#\+\?\/-])/$raw_to_url{$1}/g;
return $data;
}
# Parse content. Content may come from GET or POST requests. Also
# adapted from Lincoln Stein's CGI.pm.
sub parse_content {
my $content = shift;
my %content;
foreach (split(/[&;]/, $content)) {
my ($param, $value) = split(/=/, $_, 2);
$param = &url_decode($param);
$value = &url_decode($value);
if (exists $content{$param}) {
if (ref($content{$param}) eq 'ARRAY') {
push @{$content{$param}}, $value;
}
else {
$content{$param} = [ $content{$param}, $value ];
}
}
else {
$content{$param} = $value;
}
}
return \%content;
}