PHP md5 String and File Example

A hash function is useful for checking that something has not been changed. The md5 function is a popular hash function that can be used to generate a hash of a string of text or a file. A hash is useful since you cannot easily determine the input from the hash itself.

You may hash a file and send the hash with the file. The receiver can then rehash the file once they receive it to ensure that the file was not modified during transmission, since a modified file would generate a different hash.

Hashing a string is useful since it allows us to store something like a password without revealing the password itself. If we want to check if a password is correct we rehash the password we get and then compare it to the hash of the correct password which we already have.

If the hashes are the same, then chances are (typically more that a billion to one) that the password is the same.

Have a look at the tutorial below for examples of using PHP to hash a string and file.

PHP md5 String - Use PHP to generate a hash of a string

PHP comes with a built-in function for generating an md5 hash of a string. The function is appropriately named md5 and you simply pass the string to be hashed as the single parameter to the function.

<?php
 
$string = "Tutorial Arena";
echo md5($string);
 
?>

The result:

9124fc19337f3bb9891a23d1bd4fd3e7

That is, the md5 hash of "Tutorial Arena" is 9124fc19337f3bb9891a23d1bd4fd3e7.

PHP md5 File - Use PHP to generate a hash of a file

To generate an md5 hash of a file we use the appropriately named md5_file function.

To hash a file we can use the following code:

<?php
 
$hash = md5_file('file-to-hash.exe');
 
?>

The output we get would be the md5 hash of the file called file-to-hash.exe. Pretty simple huh? With a single call to the md5_file function, we were able to use PHP to generate the md5 hash of a file.

You can now easily check if the contents of a file has changed by rehashing the file and comparing both hashes.

PHP md5 File - Being careful with the filename parameter

Note that unless we pass an absolute filename to the md5_file function, the file will be taken as being in a location relative to the current directory of the script which is being executed. Take care to use absolute and relative paths properly when passing the file location to the function.

Using PHP, it is pretty simple to generate an md5 hash of a string or file. We hope this PHP tutorial has been useful.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...