Processing Binary Files In PHP

This little tip might be usefull for people who have recently started learning PHP and have some experience in other languages (like me).

Recently I needed to write a PHP script that would process a binary file I had created in my Delphi program. However, it turned out that fread() doesn’t work as expected – it always returns a string. So if you want to read a 32-bit integer from a binary file, doing $an_integer=fread($f, 4) won’t get the desired result – $an_integer will be a string containing some weird characters.

To correctly read/write binary data in PHP you need to use the pack() and unpack() functions.

For example, to read two cardinals (unsigned 32-bit integer) from a file:

$fp=fopen(“file.bin”,”rb”);
$bin=fread($fp,8);
$data=unpack(“V1x/V1y”,$bin);
fclose($fp)

$data["x"] and $data["y"] would contain the two numbers. The first argument to unpack() defines the structure of data to be read. See the documentation for a description of the format string.

Another thing to note is that Delphi (at least the latest versions) will save fixed-length strings as null-padded (format code “a”). Also, if you write record structures to a file you intend to process with PHP or another non-Delphi program, it is advisable to use the packed keyword to make the actual structure of binary data more predictable.

Related posts :

8 Responses to “Processing Binary Files In PHP”

  1. kuldeep says:

    can u help me about getting data form binary file
    that extension is .cgh

  2. White Shadow says:

    Sorry, I don’t know what type of data .cgh files contain and I couldn’t find this extension at http://filext.com/file-extension/chg … I’m afraid I can’t help you in this case.

  3. Andy H. says:

    That is great! Thank you very much for posting this as it is exactly what I was looking for. Nowhere else, including _PHP in a Nutshell_, does anyone mention this critical fact when working with binary data.

  4. White Shadow says:

    You’re welcome 🙂

  5. Chris says:

    Another very useful tool is bin2hex() if you’re looking to get hex data from the binary file.

  6. dayg says:

    Coming from the Java land, I have been searching for a method similar to DataOutputStream.writeUTF() for the last couple of days.

    Your tip on the PHP pack() method solved my problem.

    Thanks!

  7. ewok1 says:

    hey,

    i want to process a (graphical) binary file ending on “.exr”,
    threated as text, of course, it crushes the file.

    how could i edit this file, i want to edit some names in the .exr file?
    have you any clues to me ?! 😡

    best regards,
    Marc

  8. Jānis Elsts says:

    Take a look at OpenEXR. It’s probably the best source of information about this format.

Leave a Reply