Which PHP function to use to read a binary file into a string?

23,392

Solution 1

Try this

$handle = @fopen("/path/to/file.bin", "rb");
if ($handle) {
    while (!feof($handle)) {
        $buffer[] = fgets($handle, 400);
    }
    fclose($handle);
    $buffer[0][0] = chr(hexdec("FF")); // set the first byte to 0xFF
}
// convert array to string 

Solution 2

file_get_contents is good enough. It seems that it read files in binary mode. I have made a little PHP script to check this. No MISMATCH messages was produced.

<?php

foreach (glob('/usr/bin/*') as $binary) {
    $php = md5(file_get_contents($binary));
    $shell = shell_exec("md5sum $binary");
    if ($php != preg_replace('/ .*/s', '', $shell)) {
        echo 'MISMATCH', PHP_EOL;
    }
    else {
        echo 'MATCH', PHP_EOL;
    }
    echo $php, '  ', $binary, PHP_EOL;
    echo $shell, PHP_EOL;
}

The following note is from manual:

Note: This function is binary-safe.

Solution 3

You are looking for fread function.

fread — Binary-safe file read

Example:

$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);

Note:

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

Share:
23,392
Poonam Bhatt
Author by

Poonam Bhatt

PHP, MySQL, Ajax and jQuery developer.

Updated on July 05, 2022

Comments

  • Poonam Bhatt
    Poonam Bhatt almost 2 years

    Which PHP function to use to read a binary file into a string?

  • Poonam Bhatt
    Poonam Bhatt over 13 years
    why to set first byte to 0xFF?
  • Álvaro González
    Álvaro González over 13 years
    Under Windows, this code will treat files as plain text and will possibly corrupt the contents you read.
  • Álvaro González
    Álvaro González over 13 years
    The important bit here is the b flag in fopen().
  • Poonam Bhatt
    Poonam Bhatt over 13 years
    Thanks to Shakti Singh and Álvaro G. Vicario
  • samoz
    samoz about 11 years
    You should call fopen() with 'rb', not 'r', so that it does reads as binary instead of text.
  • Larry K
    Larry K over 5 years
    THis is the best answer. +1 for supplying a test. Well done.