Hexdump function for PHP

April 30th, 2011

When devoloping PHP applications that handle binary data it can be useful to see data as PHP will see it ‘behind the scenes’. Meaning that you can see the byte values instead of potential multibyte characters. I wrote a hexdump function that displays a PHP string in hexdump format similar to that of programs like hd or xxd (or whatever). Although there are a few additional options the basic usage is as follows.

require_once 'Hexdump.php';
hexdump($data);

You can browse the source code on GitHub. Additonally I’ve created a PEAR package for Hexdump. So you can easily install it using the PEAR command line installer. You’ll find the package itself and installation instructions on my PEAR channel

The pear package additionaly contains a command line excutable called phphd. It reads data from stdin or a file and displays it as a hexdump in the console.

Example 1

demo-default.php

<?php
require_once 'Hexdump.php';
$data = 'Metashock Hexdump';
 
// display hexdump with default settings
hexdump($data);
 
// output:
// 00000000: 4d 65 74 61 73 68 6f 63 6b 20 48 65 78 64 75 6d |Metashock.Hexdum|
// 00000010: 70                                              |p|

Example 2

demo-8bytes.php

<?php
require_once 'Hexdump.php';
 
$data = 'Metashock Hexdump';
 
// display hexdump showing 8 bytes per line
hexdump($data, 8);
 
// output:
// 00000000: 4d 65 74 61 73 68 6f 63 |Metashoc|
// 00000008: 6b 20 48 65 78 64 75 6d |k.Hexdum|
// 00000010: 70                      |p|

Example 3

demo-uppercase.php

<?php
require_once 'Hexdump.php';
 
$data = 'Metashock Hexdump';
 
// display hexdump showing 8 bytes per line
hexdump($data, 8, PHP_EOL, TRUE);
 
// output: (note that hex chars are uppercased
// 00000000: 4D 65 74 61 73 68 6F 63 |Metashoc|
// 00000008: 6B 20 48 65 78 64 75 6D |k.Hexdum|
// 00000010: 70                      |p|

Leave a Reply