Marm
Marm

Reputation: 873

PHP $_GET var with urlencode and "&" bug

In my code, I create a link like this:

$link = 'http://www.mydomain.com/'.urlencode($str).'/1';

I use url-rewriting and the rule in my htaccess file looks like this:

rewriteRule ^(.+)/(.*)$ index.php?var1=$1&var2=$2 [NC,L]

This code is working fine for almost every strings. But sometimes, the string to encode contains "&". The urlencode function encodes it corectly, but when I read the $_GET array in php, it looks like this (with $str = 'substring1&substring2'):

'var1' => 'substring1' (without "&")
'substring2' => '' (without "&")
'var2' => 1

I really need the "&" in my var. Is there a way to encode that character to make it works?

Also, I really don't know why, but sometimes I get a forbidden http error with some strings passed as var1. Apparently, they have nothing special, for exemple, "Décarie Square" makes that error. Other strings with spaces and "é" are working fine.

Upvotes: 3

Views: 2632

Answers (4)

kijin
kijin

Reputation: 8910

Apache's mod_rewrite automatically decodes urlencoded strings when it does regex matching. But it only does this once, so you should be if you urlencode your string twice. This will re-escape all of those `%' characters.

try

$link = 'http://www.mydomain.com/'.urlencode(urlencode($str)).'/1';

or stop relying on rewrite rules and use a framework that handles URL routing properly.

Oh, and there should also be htmlentities() somewhere in there.

Upvotes: 1

webbiedave
webbiedave

Reputation: 48887

Apache will automatically translate (decode) the path. You must use a different encoding or even double encoding. Base 64 will work.

Upvotes: 1

Glass Robot
Glass Robot

Reputation: 2446

Two options:

  • Urlencode the string before urlencoding the query.
  • Replace all non alphanumerical chars with a dash or underscore

As for the forbidden error are you using http auth basic or digest?

Update may mistake try using htmlentities or htmlspecialchars instead of urlencode

Upvotes: -1

SeanCannon
SeanCannon

Reputation: 78046

your $str isn't setup with key=val pairs

Try $str = 'var1=substr1&var2=substr2';

Upvotes: 0

Related Questions