Will md5(file_contents_as_string) equal md5_file(/path/to/file)?

Tom picture Tom · May 24, 2012 · Viewed 12.4k times · Source

If I do:

<?php echo md5(file_get_contents("/path/to/file")) ?>

...will this always produce the same hash as:

<?php echo md5_file("/path/to/file") ?>

Answer

prehfeldt picture prehfeldt · May 24, 2012

Yes they return the same:

var_dump(md5(file_get_contents(__FILE__)));
var_dump(md5_file(__FILE__));

which returns this in my case:

string(32) "4d2aec3ae83694513cb9bde0617deeea"
string(32) "4d2aec3ae83694513cb9bde0617deeea"

Edit: Take a look at the source code of both functions: https://github.com/php/php-src/blob/master/ext/standard/md5.c (Line 47 & 76). They both use the same functions to generate the hash except that the md5_file() function opens the file first.

2nd Edit: Basically the md5_file() function generates the hash based on the file contents, not on the file meta data like the filename. This is the same way md5sum on Linux systems work. See this example:

pr@testumgebung:~# echo foobar > foo.txt
pr@testumgebung:~# md5sum foo.txt
14758f1afd44c09b7992073ccf00b43d  foo.txt
pr@testumgebung:~# mv foo.txt bar.txt
pr@testumgebung:~# md5sum bar.txt
14758f1afd44c09b7992073ccf00b43d  bar.txt