0

I have a very simple PHP code which should read a binary file, but it doesn't work:

<?php
$fid = fopen("sampleMdl.bin","rb");
echo "No. parts: " . fread($fid, 2) . "<br/>";

fclose($fid);
?>

The first 2 bytes of sampleMdl.bin contain the integer 2. But the page displays nothing after "No. parts:". Is there actually any setting in the server that avoids PHP to read binary file?

6
  • What is in the file?! Commented Sep 4, 2013 at 7:57
  • Numerical data. As I said, the first 2 bytes contains the integer 2. Commented Sep 4, 2013 at 7:59
  • 2
    Is it actually binary data? (The bytes 02 00 are in the file) If this is the case, then you need to interpret the bytes as integers. Otherwise PHP is going to assume strings. Or is it ASCII (The bytes 30 32 = "02" are in the file). Commented Sep 4, 2013 at 8:01
  • PHP reads binary data just fine. If you just dump that binary data out as is, it's up to the viewer/browser to interpret this binary gibberish. In this case you're apparently not outputting anything that shows up when interpreted as text. Try bin2hex(fread($fid, 2)) for a change. Commented Sep 4, 2013 at 8:04
  • 1
    php.net/unpack Commented Sep 4, 2013 at 8:12

2 Answers 2

1

You read a binary integer.

$bytes = fread($fld, 2);
$n = $bytes[0] | ($bytes[1] << 8); // The number

This is a little endian format; it could also be the other way around, big endian:

$n = $bytes[1] | ($bytes[0] << 8); // The number

In this case negative numbers do not happen, so this suffices.

Sign up to request clarification or add additional context in comments.

Comments

0

Found the solution already by using a combination of unpack() and array_values():

<?php
$fid = fopen("sampleMdl.bin", "rb");
$NA = array_values(unpack("Sshort", fread(fid, 2)));
echo "No. parts: " . $NA[0] . "<br/>";

fclose($fid);
?>

Where the first 2 bytes of sampleMdl.bin is 02 00.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.