Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 203
Poonam Bhatt Avatar asked Dec 28 '10 11:12

Poonam Bhatt


People also ask

Which function is used to read from the binary file?

The fread() function is used to read a specific number of bytes from the file.

What is the function file_get_contents () useful for?

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.

What is the difference between file_get_contents () function and file () function?

The file_get_contents() function reads a file into a string. The file_put_contents() function writes data to a file.

What is fread function in PHP?

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.


2 Answers

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.

like image 174
vbarbarosh Avatar answered Oct 20 '22 10:10

vbarbarosh


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.

like image 40
Sarfraz Avatar answered Oct 20 '22 08:10

Sarfraz