PHP & MySQL | Tutorials

David Carr

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 a Ascii format.

Solution 1

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[0], $file);
fclose($pipes[0]);
$source = stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($p);

Whilst this works it does rely on being able to run shell commands on your server.

Solution 2

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 working with an image you can then output the image using base64 encoding:

base64_encode($source)

Or use headers to render directly:


header('Content-type: image/jpg');    
header('Content-Length: ' . strlen($source));    
echo base64_encode($source);
Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.