PHP Terms Files Binary Read

 

- Info:

- This tutorial shows how to use PHP to read binary data from file.

- If file doesn't exists error is returned.

- The file pointer begins at the start of the file.

- Every time you read some characters file pointer is moved for that amount.

- This tutorial is based on http://www.php.net/manual/en/function.unpack.php.

 

- Procedure:

- Create PHP Console Application Test.php.

 

Test.php

<?php

//Open file for reading.

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

if($fp==false) {

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

exit(1);

}

//Read numbers.

flock ($fp, LOCK_EX);

$bin = fread($fp,6); //Take first 6 bytes.

$data = unpack("Vx/c2chars",$bin); //Extract numbers from bytes.

$bin2 = fread($fp,4); //Take next 4 bytes.

$data2 = unpack("n*shorts",$bin2); //Extract numbers from bytes.

flock ($fp, LOCK_UN);

fclose($fp);

//Display numbers.

echo($data ["x"] ."<br/>"); //305419896 = 0x12345678

echo($data ["chars1"] ."<br/>"); //65 = 0x40

echo($data ["chars2"] ."<br/>"); //66 = 0x41

echo($data2["shorts1"]."<br/>"); //4660 = 0x1234

echo($data2["shorts2"]."<br/>"); //22136 = 0x5678

?>

 

test.txt

78 56 34 12 41 42 12 34 56 78