Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
Marm Avatar asked Sep 19 '26 16:09

Marm


2 Answers

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.

like image 88
kijin Avatar answered Sep 22 '26 08:09

kijin


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

like image 24
webbiedave Avatar answered Sep 22 '26 06:09

webbiedave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!