Flux rss

Parsing a binary file in PHP

Published by netty5, last update on Tuesday November 25, 2008 06:33:01 AM by netty5

Parsing a binary file in PHP






When using low level languages like C or Pascal, it is a common procedure, to data in a binary file (a record that can’t be translated into text).


Using C language, suppose you want to save the value 500 in a file, the code will be as follows:

#include <stdio.h>

int main()
{
    int val = 500;
    FILE *fp = fopen("file", "wb");
    
    fwrite(&val, sizeof(int), 1, fp); //store val in "file"
    fclose(fp);
    return 0;
}


When opening this particular file with a text editor, you may find it unreadable because your value is not saved as a text but in raw form binary.

But if you use PHP, it is often necessary to retrieve values stored in binary from time to time. However, PHP reads and writes in the files as text. A specific function must be used to retrieve your values.

The solution

The function unpack() can be use to solve this kind of concern.
As first argument, you must declare the type of data you want to recover and as second argument, the string from which you want to retrieve the data.

The type of data to be recovered must be detailed in the form of a symbolic nature. For example, to retrieve a signed integer, use the i character.

So if we look at the file we have record in the example above, here's the code to retrieve our value:

<?
$fp = fopen("file", "rb");
$data = fread($fp, 4); // 4 is the byte size of a whole on a 32-bit PC.
$number = unpack("i", $data);
echo $number[1]; //displays 500
?>


Important notes:

The data size may change depending on the processor architectures (Sparc, ARM, PowerPC).

A program written in C, use integers of different sizes from 32-bit to 64 bits.

The arrangement of data may not be the same. Some machines store data in Big Endian, others in Little Endian.

The data size can vary depending on the compiler.

The unpack function returns an array a little more elaborate that the one given as example below. In our case, with one requested value, our value is in the offset 1 of the array.


Equivalencies formats / data types for 32-bit PC


Here is a table comparing the data recorded by a C program compiled for a 32-bit PC.

char: c
unsigned char: C
short: s
unsigned short: S
int: I
unsigned int: L
float: f
double: d
[Shell] Viewing a binary file: Terminal illegible [Shell] Viewing a binary file: Terminal illegible When you unintentionally display contents of a binary file (e.g. cat /bin/mount | more), it may happens that the terminal displays characters which are not printable, causing the display of... en.kioskea.net/faq/sujet-942-shell-viewing-a-binary-file-terminal-illegible
Uploading of files Uploading of files Form for sending files PHP Configuration to enable upload File recovery with PHP > The PHP language allows managing files uploading through HTML form. Form for sending files The first step is to create an html... en.kioskea.net/faq/sujet-1003-uploading-of-files
Uuencode/Uudecode UUencode encoding (a contraction of Unix-to-Unix encode) is an algorithm for converting 8-bit binary data into a 7-bit format. Uuencoding was originally created for sending binary files using the email protocol uucp. The uucp system translated the... en.kioskea.net/base/uuencode-uudecode.php3
Parse error, unexpected T_STRING, expecting ',' or ';'Parse error, unexpected T_STRING, expecting ',' or ';' Example 1 How to solve the problem Example 2 In PHP, a common problem that may arise while creating a PHP file is the parse error T_String. This happens when a programmer (or a... en.kioskea.net/faq/sujet-595-parse-error-unexpected-t-string-expecting-or
PhpMyAdmin - Access denied for user root’@localhostPhpMyAdmin - Access denied for user root’@localhost To reset the rights of the root user Insert the host and password Beginners may face the problem of accessing MySql by the root user. This issue happens when the root requires you to... en.kioskea.net/faq/sujet-673-phpmyadmin-access-denied-for-user-roota-localhost
CRC data errorHi, I have been using my flash memory for a while, it was working fine, when i try to copy some files from my hard disk, sometimes some file are copied and others are not giving me an ero message : error data (cyclic redundancy check) I tried to... en.kioskea.net/forum/affich-17812-crc-data-error
Installing AVG free 8.0Hello, I have vista and i downloaded AVG FREE 8.0 when i go to get updates the message says make sure the connection parameters are set properly. where do i go to do that. thank you. need help en.kioskea.net/forum/affich-19927-installing-avg-free-8-0
Protecting PHP file accessHello, I am building a PHP application. As part of that, I stored all of the frequently used variables (such as the MySQL database login information) in a file called "config.php" and then simply put "include 'config.php';" at the beginning... en.kioskea.net/forum/affich-15891-protecting-php-file-access
Download NewObjects ActiveX Pack1NewObjects ActiveX Pack1 is a pack ice of components ActiveX. He allows management or access of files in binary mode and text. Recording is based on an access haphazardly in fluxes and binary files. It supports combined files OLE.This pack ice is... en.kioskea.net/telecharger/telecharger-890-newobjects-activex-pack1
Download Core FTP LEFeatures like SFTP (SSH), SSL, TLS, IDN, browser integration, site to site transfers, FTP transfer resume, drag and drop support, file viewing & editing, firewall support, custom commands, FTP URL parsing, command line transfers, filters, and much,... en.kioskea.net/telecharger/telecharger-232-core-ftp-le
Download Instant File Name SearchAlthough mode searches already exist on Windows, sometimes more definite tools for specific tasks are needed. Instant Name Search Goes off search files by name on your computer or on a network instantly. It supports the Boolean operators (AND,or,... en.kioskea.net/telecharger/telecharger-630-instant-file-name-search
Swedish court convicts man of file sharingA student downloads music from a file-sharing website in 2001. A Swedish court has handed down a suspended sentence and a 10,000-kronor (1,655-dollar, 1,070-euro) fine to a man found guilty of sharing some 4,500 music files and 30 films on the... en.kioskea.net/actualites/swedish-court-convicts-man-of-file-sharing-10338-actualite.php3
Operating systems - File formats and extensions Comment: The list below is not exhaustive and certain extension names may have several functionalities. As for the programmes proposed for using these files, they are not necessarily the only ones or the most appropriate ones. Extension Description... en.kioskea.net/systemes/format.php3
Operating systems - Files A file is a suite of binary information, i.e. a suite from 0 to 1. This file may be stored in order to keep a record of this information. A text file is a file comprising characters stored in the form of octets. This file is saved on the hard drive... en.kioskea.net/systemes/fichier.php3
BinHex encoding BinHex encoding (a contraction of binary-to-hexadecimal) is a proprietary algorithm owned by Apple for converting 8-bit binary data into a 7-bit format. BinHex encoding, designed for Macintosh systems, is used to preserve file attributes, and... en.kioskea.net/base/binhex.php3