ASCII to Binary in PHP

David Carr

2 min read - 8th Jul, 2020

Table of Contents

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:

```php header('Content-type: image/jpg');
header('Content-Length: ' . strlen($source));
echo base64_encode($source);

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.