Justin
Justin

Reputation: 45350

PHP encode e-mail address

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:

 [email protected] => ENCODE => n6bvJjdh7w6QbdVB373483ydbKus7Qx
 n6bvJjdh7w6QbdVB373483ydbKus7Qx => DECODE => [email protected]

Is this even possible?

Upvotes: 5

Views: 7340

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173562

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.

Upvotes: 7

sachleen
sachleen

Reputation: 31131

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

Another option is bin2hex() and hex2bin()

Upvotes: 2

Related Questions