Using hash_file() to Generate a File Hash in PHP
This article explains PHP's hash_file() function, its parameters, return values, security use cases, and provides a complete example demonstrating how to compute an MD5 hash of a file, including code snippets and expected output.
hash_file() generates a hash value for the contents of a given file using a specified algorithm.
The function takes three parameters: $algo (the hash algorithm name, e.g., "md5" or "sha256"), $filename (the path to the file, supporting fopen wrappers), and an optional $raw_output boolean that determines whether the result is raw binary data (TRUE) or a lowercase hexadecimal string (FALSE, default).
It is useful for constant‑time string comparisons to prevent timing attacks, such as verifying password hashes produced by crypt() .
Parameters
algo : name of the hash algorithm, e.g., "md5", "sha256", "haval160,4".
filename : path to the file to be hashed; fopen wrappers are supported.
raw_output : set to TRUE to get raw binary output, FALSE for a lowercase hex string.
Return value
If $raw_output is TRUE, the function returns the raw binary digest; otherwise it returns a lowercase hexadecimal string (e.g., 32‑character MD5 hash).
Example
<?php
/* Create a file to hash */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');
echo hash_file('md5', 'example.txt');
?>Running the example outputs:
5c6ffbdd40d9556b73a21e63c3e0e904Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.