I need to register a document or image in hexadecimal format in the database and then retrieve this data by converting it back to the correct format.
I need to register a document or image in hexadecimal format in the database and then retrieve this data by converting it back to the correct format.
PHP already has its own functions for this:
string hex2bin ( string $data )
which converts the string hehadecimal passed in the parameter $data
into a binary format, which can be saved in a BLOB
in the database, or convert data from a Varchar to string , if you are storing in hex but using the data in bytes ...
... and also the
string bin2hex ( string $str )
which converts the string into $str
and returns the corresponding hexadecimal, so when you retrieve the data from BLOB
, you can convert them back to hex, or if you are using "ao otherwise, you can take data in bytes and use this function to convert the data to a string hex, which can be stored in a Varchar.
To use them, it depends on your case study. The important thing is to know that when you get the data in hexadecimal, you can pass them to binary with hex2bin
, effectively reducing its space by 50%, to store a BLOB
in the database, and when recovering data from DB, just use bin2hex
to have the data in hex again.
<?php
$data = '546573746520646520636f6e76657273616f';
echo hex2bin( $data );
?>
Output:
Teste de conversao
<?php
$data = file_get_contents( 'teste.jpg' );
echo bin2hex( $data );
?>
Output:
FFD8FFE102DE45786966000049492A00080000000F000001030001000000100A...