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.
For example, to read two cardinals (unsigned 32-bit integer) from a file:
$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 :