PHP encode e-mail address

2019-02-10 15:33发布

问题:

I need a way in PHP to encode an e-mail address only using a-zA-Z0-9 so basically encoded without any special characters, but then be able to decode it back to the original.

Example:

 john+doe@mydomain.com => ENCODE => n6bvJjdh7w6QbdVB373483ydbKus7Qx
 n6bvJjdh7w6QbdVB373483ydbKus7Qx => DECODE => john+doe@mydomain.com

Is this even possible?

回答1:

You can do a web safe base64 encode:

// encode
$email_encoded = rtrim(strtr(base64_encode($email), '+/', '-_'), '=');

// decode
$email_decoded = base64_decode(strtr($email_encoded, '-_', '+/'));

It converts the + and / from the base64 alphabet in the more harmless - and _. The encoding step also removes the trailing = characters when needed.



回答2:

If you allow the equal sign, you can use base64_encode() and base64_decode()

Another option is bin2hex() and hex2bin()



标签: php hash encode