ASCII to Binary in PHP

David Carr

Tutorials PHP & MySQL

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 in 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're 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);

 

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.