Convert string to binary then back again using PHP

Is there a way to convert a string to binary then back again in the standard PHP library?

To clarify what I'm trying to do is store a password on a database. I'm going to convert it first using a hash function then eventually store it as binary.


I've found the best way is to use this function. Seems to hash and output in binary at the same time.

http://php.net/manual/en/function.hash-hmac.php


Solution 1:

You want to use pack and base_convert.

// Convert a string into binary
// Should output: 0101001101110100011000010110001101101011
$value = unpack('H*', "Stack");
echo base_convert($value[1], 16, 2);

// Convert binary into a string
// Should output: Stack
echo pack('H*', base_convert('0101001101110100011000010110001101101011', 2, 16));

Solution 2:

Yes, sure!

There...

$bin = decbin(ord($char));

... and back again.

$char = chr(bindec($bin));

Solution 3:

A string is just a sequence of bytes, hence it's actually binary data in PHP. What exactly are you trying to do?

EDIT

If you want to store binary data in your database, the problem most often is the column definition in your database. PHP does not differentiate between binary data and strings, but databases do. In MySQL for example you should store binary data in BINARY, VARBINARY or BLOB columns.

Another option would be to base64_encode your PHP string and store it in some VARCHAR or TEXT column in the database. But be aware that the string's length will increase when base64_encode is used.