Search code examples
perlcgi

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".


Solution

  • 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 the OP wasn't properly constructed; the brand parameter wasn't set to Bell & Ross. 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 );