PHP encrypt and decrypt string to be url friendly

10,340

Solution 1

https://stackoverflow.com/a/30189841/1325575 explains this in-depth.

However, the short version, which requires no 3rd party installs:

  1. Use openssl_encrypt for encryption
  2. Use openssl_decrypt for decryption

I'm confident that with those 3 links you're gonna find what you're after.

Solution 2

I would suggest just using the hashids library which is pretty popular and what many url shortening services use. While it isn't really "encryption", it is likely good enough to hide a user's id number in a url. Example:

$userID = 1234;
$hashids = new Hashids\Hashids('some random secret string');

//encode the user id
$encodedID = $hashids->encode($user_id);

//on the other page, decode the user id
$decodedID = $hashids->decode($encodedID);
Share:
10,340
Dennis
Author by

Dennis

Updated on June 04, 2022

Comments

  • Dennis
    Dennis about 2 years

    I am trying to figure out a way to encrypt a user id number. My idea is to encrypt the id ( between 1 and 5 characters ) in combination with some letters ( like _wordtouse ). The only two requirements are

    1. The crypted version can only contain a maximum of 15 characters
    2. I need to be able to decrypt the string on a different page

    The reason for all of this is that i am trying to "hide" user id numbers when someone enters a users profile. So i am trying to find a way to deliver an encrypted version of the user id through the url as a get parameter.

    Does anyone have an idea on how to solve this?

  • Machavity
    Machavity about 7 years
    If the question has been answered elsewhere you should delete your answer and flag it as a duplicate
  • Machavity
    Machavity about 7 years
    If the question has been answered elsewhere you should delete your answer and flag it as a duplicate
  • lloiacono
    lloiacono about 7 years
    @Machavity, the previous answer advices to use mcrypt which is abandoned, that is why I added which alternatives to use IMO
  • Dennis
    Dennis about 7 years
    @Nino Thank you very much.
  • The Onin
    The Onin about 7 years
    Seems cool, a sample would be nice tho.
  • Jonathan Kuhn
    Jonathan Kuhn about 7 years
    @NinoŠkopac I did include an example in the answer. There is also quite a lot more information on their own website which I linked to.
  • The Onin
    The Onin about 7 years
    I'm sorry, I meant an example of the output.
  • Anas Naim
    Anas Naim over 4 years
    I used hashids library in 2 large projects, it's an amazing library!