Database Reference
In-Depth Information
Perl. The Perl CGI.pm module provides two methods, escapeHTML() and escape() ,
that handle HTML-encoding and URL-encoding. There are three ways to use these
methods to encode a string $str :
• Invoke escapeHTML() and escape() as CGI class methods using a CGI:: prefix:
use CGI ;
printf "%s\n%s\n" , CGI:: escape ( $str ), CGI:: escapeHTML ( $str );
• Create a CGI object and invoke escapeHTML() and escape() as object methods:
use CGI ;
my $cgi = new CGI ;
printf "%s\n%s\n" , $cgi -> escape ( $str ), $cgi -> escapeHTML ( $str );
• Import the names explicitly into your script's namespace. In this case, neither a CGI
object nor the CGI:: prefix is necessary and you invoke the methods as standalone
functions. The following example imports the two method names in addition to
the set of standard names:
use CGI qw(:standard escape escapeHTML) ;
printf "%s\n%s\n" , escape ( $str ), escapeHTML ( $str );
I prefer the last alternative because it is consistent with the CGI.pm function call inter‐
face that you use for other imported method names. Just remember to include the en‐
coding method names in the use CGI statement for any Perl script that requires them,
or you'll get “undefined subroutine” errors when the script executes.
The following code reads the rows of the phrase table and produces hyperlinks from
them using escapeHTML() and escape() :
my $stmt = "SELECT phrase_val FROM phrase ORDER BY phrase_val" ;
my $sth = $dbh -> prepare ( $stmt );
$sth -> execute ();
while ( my ( $phrase ) = $sth -> fetchrow_array ())
{
# URL-encode the phrase value for use in the URL
my $url = "/cgi-bin/mysearch.pl?phrase=" . escape ( $phrase );
# HTML-encode the phrase value for use in the link label
my $label = escapeHTML ( $phrase );
print a ({ - href => $url }, $label ), br ();
}
Ruby. The Ruby cgi module contains two methods, CGI.escapeHTML() and CGI.es
cape() , that perform HTML-encoding and URL-encoding. However, both methods
raise an exception unless the argument is a string. To deal with this, apply the to_s
method to any argument that might not be a string, to force it to string form and convert
nil to the empty string. For example:
Search WWH ::




Custom Search