CdB
CdB

Reputation: 4908

php encode string and vice-versa

I have some entities(objects), each one having an id(unique) and a name.
When i want to display oneof these , i have a url like www.domain.com/view/key:xxx.
The key is just the id of the entity encoded with base64_encode, so it's not straightforward from the url what the id is.

What i'm trying to do now (due to the projects specifications) is have the key contain only numbers and letters (base64_encode provides a result like eyJpZCI6IjM2In0= or eyJpZCI6IjM2In0%3D after url encode).

Is there a simple alternative to this? It's not a high-security issue - there are many ways the id can be revealed -, i just need to have a key that contains only letters and numbers that is produced by the entity ID (maybe in combination with its name) that can be decoded to give me the ID back.

All different encode methods i've found can contain special characters as well.
Any help here?
Thanks in advance

Upvotes: 5

Views: 15181

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173642

This answer doesn't really apply encryption, but since your question was tagged with encoding as well ...

Since PHP 5 you can use bin2hex:

$s = base64_decode('eyJpZCI6IjM2In0=');
echo bin2hex($s);

Output:

7b226964223a223336227d

To decode:

$s = hex2bin($data);

Or:

$s = pack('H*', $data);

Btw, if the id is sensitive you might want to consider tamper proofing it as an alternative to full-blown encryption.


Forgot to mention how you can make base64 encoded data URL safe:

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

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

Upvotes: 8

Steve
Steve

Reputation: 642

There are many PHP encoding/decoding functions. You can find a lot here and here.

Alternatively just get rid of the = at the end of the base64_encode and add it in the PHP code for base64_decode to find the ID.

Upvotes: 0

Related Questions