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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using hash_file() to Generate a File Hash in PHP

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:

5c6ffbdd40d9556b73a21e63c3e0e904
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

securityPHPFile Hashinghash_file
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.