OK, not having anything more at my disposal than CGI.pm, I'm planning on using these two functions to clean input data, and escape javascript output.
I've set the functions up to accept/return either a single string or an array of strings
Is there a faster way to do this? Am I setting myself up for problems?
update: replaced '#' with '&' in test example
use strict;
use warnings;
# strip any non-safe URL characters
# Note: This is not Data validation! Other
# code must verify/edit expected results
sub SafeURL {
my @args = @_;
local $_;
foreach (@args) {
s/[^\w\d.\@-]//gi if defined;
}
return wantarray ? @args : pop @args;
}
# Note: escape html covered by CGI escapeHTML()
# escape any non-safe javascript characters
sub EscapeJavaScript {
my @args = @_;
local $_;
foreach (@args) {
s/([^\w\d.\@-])/uc sprintf("%%%02x",ord($1))/egi
if defined;
}
return wantarray ? @args : pop @args;
}
#####################
# test subs
my @array = qw(
blah@&blah.blah/<test>
lalalalal12340as-rqweousn
//hokey/pokey
);
foreach (@array) {
my $result1 = SafeURL($_);
my $result2 = EscapeJavaScript($_);
print "string: $_\n SafeURL: $result1\n EscapeJavaScript: $resul
+t2\n";
}
print "SafeURL array test: " . join(', ', SafeURL(@array)) . "\n";
print "EscapeJavaScript array test: " . join(', ', EscapeJavaScript(@a
+rray)) . "\n";
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.