Sameer Borate has a new post to his Code Deisel blog showing how to unpack binary data in PHP making use of the pack and unpack functions.
Working with binary files in PHP is rarely a requirement. However when needed the PHP ‘pack’ and ‘unpack’ functions can help you tremendously. To set the stage we will start with a programming problem, this will keep the discussion anchored to a relevant context. The problem is this : We want to write a function that takes a image file as an argument and tells us whether the file is a GIF image; irrelevant with whatever the extension the file may have. We are not to use any GD library functions.
He starts by briefly covering the "metadata" that binary files contain in their headers about the type of file and, more specifically, what the content for a GIF looks like. He follows this with an example of using unpack to provide a readable version of the file's binary content. He then uses this in an
is_gif function to read the contents of a file, check the header format and ensure the version is either
GIF89a. He also includes the code for another method to get attributes about the file like height, width and the aspect ratio. He ends the post with more details on the contents of the header and what each character means.