ASCII to Binary in PHP
Recently I inherited a project where all file attachments were stored in a database table in the format of `0xFFD8FFE000104A4649` I need PHP to be able to read and serve this data.
My first thought was to try using base64_decode in case this was in a base64 encoding format. It wasn't.
Turns out it's in Ascii format.
The below block converts the data into a format PHP can read by issuing a shell command xxd with -r and -p options passing the command to a proc_open command to run and then using fwrite to return the data to `$source`
$file = '0xFFD8FFE000104A4649...'; //var containing the source data $desc = array( 0 => array('pipe', 'r'), // 0 is STDIN for process 1 => array('pipe', 'w') // 1 is STDOUT for process ); $cmd = "xxd -r -p -"; $p = proc_open($cmd, $desc, $pipes); fwrite($pipes, $file); fclose($pipes); $source = stream_get_contents($pipes); fclose($pipes); proc_close($p);
Whilst this works it does rely on being able to run shell commands on your server.
Another way is to use hex2bin function and remove the 0x characters from the data, this essentially does the same thing but the hex2bin does the heavy lifting.
$source = hex2bin(ltrim(rtrim($file), '0x'));
If you're working with an image you can then output the image using base64 encoding:
Or use headers to render directly:
header('Content-type: image/jpg'); header('Content-Length: ' . strlen($source)); echo base64_encode($source);