Alex
Alex

Reputation: 67698

PHP: Very simple Encode/Decode string

Is there any PHP function that encodes a string to a int value, which later I can decode it back to a string without any key?

Upvotes: 2

Views: 11349

Answers (6)

Lars Jansen
Lars Jansen

Reputation: 113

There is no function for PHP but I recently wrote a class to encrypt and decrypt a string in PHP. You can look at it at: https://github.com/Lars-/PHP-Security-class

Upvotes: 1

fawaz ali
fawaz ali

Reputation: 11

op through the individual letters' ordinal value and display that as a two-digit hexadecimal. You can then convert these hexadecimals back to the ordinal values of the individual characters. Don't know what kind of characters are you about to encode, possibly you will need to use 4-characters per letter (e.g. String Peter would become 00700065007400650072 ) Well... have fun with that, I still don't really see the

Upvotes: 1

pr1001
pr1001

Reputation: 21962

Sure, you can convert strings to numbers and vice versa. Consider:

$a = "" + 1
gettype($a) // integer
$b = "$a"
gettype($b) // string

You can also do type casting with settype().

If I misunderstood you and you want to encode arbitrary strings, consider using base64_encode() and bas64_decode(). If you want to convert the base 64 string representation to a base 10 integer, simply use base_convert().

Upvotes: 5

Peter Perháč
Peter Perháč

Reputation: 20792

i'm convinced that what you think you want to do is not really what you want to do. :-) this just sounds like a silly idea. As another user has asked before:) what do you need this for? What are your intentions?

Well now that you mentioned that numbers and a-z letter are acceptable, then I have one suggestion, you could loop through the individual letters' ordinal value and display that as a two-digit hexadecimal. You can then convert these hexadecimals back to the ordinal values of the individual characters. Don't know what kind of characters are you about to encode, possibly you will need to use 4-characters per letter (e.g. String Peter would become 00700065007400650072 ) Well... have fun with that, I still don't really see the rationale for doing what you're doing.

Upvotes: 1

slifty
slifty

Reputation: 13811

I would suspect not, since there are far more possible string combinations than integers within the MAX_INT.

Does it have to be an integer?

Upvotes: 1

Bart van Heukelom
Bart van Heukelom

Reputation: 44114

And int has 4 or 8 bytes depending on the platform, and each character in a string is one byte (or more depending on encoding). So, you can only encode very small strings to integers, which basically makes the answer to your question: no.

What do you want to accomplish?

Upvotes: 2

Related Questions