0

I am using the base64_encode for sending the numeric id to url, base64_encode($list_post['id']); up to 99 its working fine, but after 99 its produce wrong encoded string.

the last character in encoded string is = (equal sign), but when the number more than 99, for example 100 it don't show = (equal sign) at the end.

Muhammad
  • 267
  • 4
  • 9
  • 24
  • encoding for 99 is OTc=, its ok. but for 103 its generate MTAz. at the end there is a = sign missing. then encoded string is wrong. – Muhammad May 03 '14 at 18:23
  • http://www.base64encode.org/ if you try that here, you get exactly the same result, so it's not a PHP's fault, there must be a problem somewhere else. Can you paste some more code? – JohnKiller May 03 '14 at 19:02
  • every thing is ok, up to 99 but when this increase to 3 digits, for example 100 , 101, 102 it gives error. – Muhammad May 03 '14 at 19:06

2 Answers2

2

Take a look at how padding in base64 works: http://en.wikipedia.org/wiki/Base64#Padding

The padding (the "=" character) is not always needed and in some implementations is not even mandatory.

EDIT: ok from your comments I see that you are using the base64 encoded string in a URL like this:

http://example.com/path/OTC=

The base64 encoding includes chars that have a special meaning in URLs so you need to use a slightly modified function (https://stackoverflow.com/a/5835352/2737514):

function base64_url_encode($input) {
    return strtr(base64_encode($input), '+/=', '-_,');
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_,', '+/='));
}

However, since your code works for some numbers, maybe there is a problem with the .htaccess not parsing the url correctly, or the PHP code that interpretes the URL. I can't help more than this without seeing some other code.

Community
  • 1
  • 1
JohnKiller
  • 2,008
  • 18
  • 28
  • Good answer! I didn't knew about the special meaning of the `=` in base64 – hek2mgl May 03 '14 at 18:18
  • But I am facing problem, with out = sign. I used the following to decode: if(isset($_POST['id']) && !empty($_POST['id'])) { $id = base64_decode($_POST['id']); } – Muhammad May 03 '14 at 18:43
  • Dear JohnKiller, here is .htaccess: RewriteEngine on RewriteRule ^([-@./#&+\w\s]*)/([A-Z]+=)$ /details_post.php?id=$2 [NC,L] – Muhammad May 03 '14 at 19:35
1

it seems working fine for me

Can you please test with following code

echo base64_encode(101);
echo base64_decode(base64_encode(101));

DEMO

Base64-encoded data takes about 33% more space than the original data.

So these numbers shouldnt be a problem

maj
  • 572
  • 5
  • 8