Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

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);

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

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

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

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