PHP - urlencoded() ampersand in url perceived as actual ampersand

1.3k views Asked by At

There is an dummy example PHP application which shows what causes me problems.

<?PHP
echo ((isset($_GET['P'])) ? print_r($_GET) : "<a href='http://example.com/a.php?P=" . urlencode('One & Two') . "'>One & Two</a>");

?>


If we visit page without P parameter page will output:
http://example.com/One+%26+Two
And that's fine, but if we visit the link, script will return:

Array

    (
        [P] => One
        [Two] => 
    )

And that's obviously WRONG.
In real application, in url is submitted about 30 char long alphanumeric string which contains special letters(Swedish).
Edit: In my real application I use URL rewrite:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule ^(.*)$ ../example.php?s=$1 [L,QSA]
</IfModule>

Can that be the cause? - Confirmed. It was the issue. See my answer below.

3

There are 3 answers

6
Panama Jack On BEST ANSWER

You need to send your URL using the % to escape the ampersand. Try it like this 'One %26 Two'

<?PHP
echo ((isset($_GET['P'])) ? print_r($_GET) : "<a href='http://example.com/a.php?P=One %26 Two'>One & Two</a>");
?>
3
Imtiaz Pabel On

you can follow this.if your array is like that

$data = array('p'=>'one',
          'q'=>'two');

you can build url like this

echo http_build_query($data)

it will give output like this

p=one&q=two
3
xZero On

I found the problem. Problem was laying out of PHP powers.
It was problem with URL rewrite:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule ^(.*)$ ../example.php?s=$1 [L,QSA]
</IfModule>

The new working version:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule ^(.*)$ ../example.php?s=$1 [B,L,QSA]
</IfModule>

Reference: data being stripped off after ampersand in URL even when using urlencode