Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

md5

md5-file

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") ?>

like image 682
Tom Avatar asked May 24 '12 13:05

Tom


People also ask

Does renaming a file change the MD5?

Changing a filename will have no affect on its md5sum in Linux.

How do I change the MD5 checksum of a file?

You can not change md5sum of a file as long as the contents of the files are same. And that is the sole purpose of it. You can change the md5sum value of a file by making any change in its content only.


1 Answers

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 
like image 148
prehfeldt Avatar answered Oct 04 '22 00:10

prehfeldt