How to use fread() and unpack() Functions In PHP

For larger files, or when you need more control over the reading process (such as reading in chunks), fread in combination with fopen and unpack can be used.

PHP




<?php
  
$filePath = 'gfg.txt';
  
$fileHandle = fopen($filePath, 'rb');
$fileSize = filesize($filePath);
$fileContent = fread($fileHandle, $fileSize);
  
$byteArray = unpack('C*', $fileContent);
  
fclose($fileHandle);
  
print_r($byteArray);
  
?>


Output

Array ( [1] => 87 [2] => 101 [3] => 108 [4] => 99 [5] => 111 [6] => 109 [7] => 101 [8] => 32 [9] => 116 [10] => 111 [11] => 32 [12] => 71 [13] => 101 [14] => 101 [15] => 107 [16] => 115 [17] => 102 [18] => 111 [19] => 114 [20] => 71 [21] => 101 [22] => 101 [23] => 107 [24] => 115 [25] => 13 [26] => 10 [27] => 87 [28] => 101 [29] => 108 [30] => 99 [31] => 111 [32] => 109 [33] => 101 [34] => 32 [35] => 116 [36] => 111 [37] => 32 [38] => 71 [39] => 101 [40] => 101 [41] => 107 [42] => 115 [43] => 102 [44] => 111 [45] => 114 [46] => 71 [47] => 101 [48] => 101 [49] => 107 [50] => 115 [51] => 13 [52] => 10 [53] => 72 [54] => 101 [55] => 108 [56] => 108 [57] => 111 [58] => 32 [59] => 87 [60] => 101 [61] => 108 [62] => 99 [63] => 111 [64] => 109 [65] => 101 )

Here, fopen opens the file in binary read mode (‘rb’), filesize gets the size of the file, and fread reads the file content based on the provided size. unpack then converts this content into a byte array.

How to Convert File Content to Byte Array in PHP ?

Converting file content to a byte array in PHP is a useful technique for various applications, including file manipulation, data processing, and when working with binary files like images or PDFs. PHP offers multiple ways to read file content and convert it into a byte array, providing flexibility to handle different scenarios effectively.

Similar Reads

Using file_get_contents() and unpack() Functions

One of the simplest ways to convert file content to a byte array in PHP is by using the file_get_contents() function to read the file content as a string, and then using unpack() function to convert the string to a byte array....

Using fread() and unpack() Functions

...

Using File and Array Mapping

For larger files, or when you need more control over the reading process (such as reading in chunks), fread in combination with fopen and unpack can be used....