Muhammad
Muhammad

Reputation: 307

base64_encode() limitation in php

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.

Upvotes: 0

Views: 7011

Answers (2)

JohnKiller
JohnKiller

Reputation: 2008

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.

Upvotes: 2

maj
maj

Reputation: 582

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

Upvotes: 1

Related Questions