title: Reading Binary Files in PHP
body: <p>Is there any comprehensive information on how binary files can be read? I found information on the PHP website (<a href="http://www.php.net/manual/en/function.pack.php" rel="nofollow noreferrer">http://www.php.net/manual/en/function.pack.php</a>) but I am struggling to understand on how to handle "typedef struct" and struct uses.</p>
  
  <p>I have a long binary file with many blocks, each block can be represented us C struct. This C struct has various "typedef struct" similar to what i have come up with below:</p>
  
  <pre><code>typedef struct
  { 
   unsigned char Day;
   unsigned char Month;
   unsigned char Year;
  } DATE_OF_BIRTH;
  #define USER_TYPE 5
  DATE_OF_BIRTH Birth[2];\
  </code></pre>
  
  <hr>
  
  <p>EDIT:</p>
  
  <p>I have a structure below, this is a part of a bigger structure</p>
  
  <pre><code>typedef struct FILE_HEADER_tag
  {
      int Type;
      int Version;
      unsigned long Model;
      unsigned long Number;
      int Class;
  
      int TemplateLoaded;
      char TemplateName[32];
      RTC_TIME_DATE StartTime;
      RTC_TIME_DATE CurrentCal;
      RTC_TIME_DATE OriginalCal;
      TEMPLATE_SETTINGS;
      int EndType;
  } FILE_HEADER;
  
  typedef struct
  {
   unsigned char Second;
   unsigned char Minute;
   unsigned char Hour;
   unsigned char Day;
   unsigned char Month;
   unsigned char Year;
  } RTC_TIME_DATE;
  </code></pre>
  
  <p>The binary file is full of line breaks and I was able to decode the first line of it, which returned correct: type, version, model, number and a class. I think I have also decoded two next variable, but i am not sure of it because StartTime returns some gibberish.</p>
  
  <p>At the moment I am looping through the lines from the binary file and trying to unpack each one:</p>
  
  <pre><code>$i = 1;
  while (($line = fgets($handle)) !== false) {
      // process the line read.
      var_dump($line);
      if($i == 1) {
          $unpacked = unpack('iType/iVersion/LModel/LNumber/iClass/iTemplateLoaded', $line );
      }if($i == 2) {
          $i++;
          continue;
      }if($i == 3) { 
          $unpacked = unpack('C32TemplateName/CStartTime[Second]/CStartTime[Minute]/CStartTime[Hour]/CStartTime[Day]/CStartTime[Month]/CStartTime[Year]', $line);
      }
  
      print "&lt;pre&gt;";
      var_dump($unpacked);
      print "&lt;/pre&gt;";
  
      $i++;
  
      if($i == 4) { exit; }
  }
  </code></pre>