Tarun Vikash Tarun Vikash -4 years ago 86
Perl Question

how do I handle '&' in perl cgi url parameter where the parameter value contains an '&' sign

I am trying to pass parameters in URL and reading the parameters with param().
one of my parameter values contain an '&' sign, hence while reading the value through param() it skips the part after '&'.
Is there any way I can use this method without compromising the value that contain '&'?

Example:

http://someurl/?brand=Bell%20&%20Ross&category=Wrist%20Watch%20Dealers&qq_cat_id=8798798

The value for the parameter brand is coming "Bell" rather than "Bell & Ross".

Answer Source

You don't have to do anything special to handle param values that contain &. For example, $cgi->param('brand') would return Bell & Ross for

http://someurl/?brand=Bell%20%26%20Ross&category=Wrist%20Watch%20Dealers&qq_cat_id=8798798
                             ^^^

The problem is that the url in question wasn't properly constructed. All of the following will correctly construct the url:

use URI::Escape qw( uri_escape );

my $url = 'http://someurl/';
$url .= "?" . join('&', 
   join('=', map { uri_escape($_) } brand     => $brand),
   join('=', map { uri_escape($_) } category  => $category),
   join('=', map { uri_escape($_) } qq_cat_id => $qq_cat_id),
);

or

use URI qw( );

my $url = URI->new('http://someurl/');
$url->query_form(
   brand     => $brand,
   category  => $category,
   qq_cat_id => $qq_cat_id,
);

or

use URI             qw( );
use URI::QueryParam qw( );

my $url = URI->new('http://someurl/');
$url->query_param_append( brand     => $brand );
$url->query_param_append( category  => $category );
$url->query_param_append( qq_cat_id => $qq_cat_id );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download