Which PHP function to use to read a binary file into a string?
The fread() function is used to read a specific number of bytes from the file.
The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string.
The file_get_contents() function reads a file into a string. The file_put_contents() function writes data to a file.
The fread() function reads from an open file. The fread() function halts at the end of the file or when it reaches the specified length whichever comes first. It returns the read string on success.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With