How To Read a File in Binary Mode


How To Read a File in Binary Mode? - PHP Script Tips - Reading and Writing Files



If you have a file that stores binary data, like an executable program or picture file, you need to read the file in binary mode to ensure that none of the data gets modified during the reading process. You need to:

  • Open the file with fopen($fileName, "rb").
  • Read data with fread($fileHandle,$length).

Here is a PHP script example on reading binary file:

$in = fopen("/windows/system32/ping.exe", "rb");
$out = fopen("/temp/myPing.exe", "w");
$count = 0;
while (!feof($in)) {
  $buffer = fread($in,64);
print("About ".($count*64)." bytes read.\n"); 

This script will print:

About 16448 bytes read.

This script actually copied an executable program file ping.exe in binary mode to new file. The new file should still be executable. Try it: \temp\myping

2007-04-23, 5319👍, 0💬