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

Poonam Bhatt picture Poonam Bhatt · Dec 28, 2010 · Viewed 19.9k times · Source

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

Answer

vbarbarosh picture vbarbarosh · Mar 22, 2015

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.