PHP

Hash Large File Without Loading It

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Compute the SHA-256 of a multi-gigabyte file by streaming it through hash_init / hash_update_stream — no memory blow-up. Useful for backup verification or torrent-style integrity checks.
PHP
Raw
<?php
function hashFile(string $path, string $algo = 'sha256'): string {
    $ctx = hash_init($algo);
    $fh  = fopen($path, 'rb');
    if (!$fh) throw new RuntimeException("Cannot open $path");
    try {
        hash_update_stream($ctx, $fh);   // streams in chunks internally
    } finally {
        fclose($fh);
    }
    return hash_final($ctx);
}

echo hashFile('/var/log/big.log');                 // 64-char hex SHA-256
echo hashFile('/backup/db.dump.gz', 'sha512');     // 128-char hex SHA-512
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.