PHP Terms Files Binary Write

 

- Info:

- This tutorial shows how to use PHP to write to a binary file.

- If file exists data is deleted.

If file doesn't exists new one is created.

File pointer is at the begining of the file.

- Saving number in little endian format means that bytes are stored in reverse order, from lower to higher byte values.

For example bytes of hexadecimal number 0x12345678 would be stored like this 78 56 34 12.

- Repeater arguments allow you to define binary type for sequence of values.

- This tutorial is based on http://php.net/pack.

 

- Procedure:

- Create PHP Console Application Test.php.

 

Test.php

<?php

$fp = fopen("test.txt", 'wb'); //Create FilePointer for writing to file.

if($fp==false) {

print("Unable to open or create file.");

exit(1);

}

flock ($fp, LOCK_EX);

$binaryData = pack("Vc2n*", 0x12345678, 65, 66, 0x1234, 0x5678);

fwrite($fp, $binaryData);

flock ($fp, LOCK_UN);

fclose($fp);

?>

 

test.txt

78 56 34 12 41 42 12 34 56 78

 

- Repeater Arguments:

 

Symbol

Example

Description

 

Number

c2

Next 2 values are of type "c-signed char"

 

*

n*

Remaining values are of type "n-unsigned short"

 

- Binary Types:

 

Code

Description

Size

 

a

NUL-padded string

 

 

A

SPACE-padded string

 

 

h

Hex string, low nibble first

 

 

H

Hex string, high nibble first

 

 

c

signed char

 

 

C

unsigned char

 

 

s

signed short

always 16 bit, machine byte order

 

S

unsigned short

always 16 bit, machine byte order

 

n

unsigned short

always 16 bit, big endian byte order

 

v

unsigned short

always 16 bit, little endian byte order

 

i

signed integer

machine dependent size and byte order

 

I

unsigned integer

machine dependent size and byte order

 

l

signed long

always 32 bit, machine byte order

 

L

unsigned long

always 32 bit, machine byte order

 

N

unsigned long

always 32 bit, big endian byte order

 

V

unsigned long

always 32 bit, little endian byte order

 

f

float

machine dependent size and representation

 

d

double

machine dependent size and representation

 

x

NUL byte

 

 

X

Back up one byte

 

 

@

NUL-fill to absolute position