Search code examples
phpencryptionencode

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


Solution

  • 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, '-_,', '+/='));
    }