Created
March 26, 2018 12:35
-
-
Save lcherone/05790c620e7fc52dd6fa5343d0707b5d to your computer and use it in GitHub Desktop.
hash_file_multi() hash a single file with multiple algorithms PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function hash_file_multi($algos = [], $filename) { | |
if (!is_array($algos)) { | |
throw new \InvalidArgumentException('First argument must be an array'); | |
} | |
if (!is_string($filename)) { | |
throw new \InvalidArgumentException('Second argument must be a string'); | |
} | |
if (!file_exists($filename)) { | |
throw new \InvalidArgumentException('Second argument, file not found'); | |
} | |
$result = []; | |
$fp = fopen($filename, "r"); | |
if ($fp) { | |
// ini hash contexts | |
foreach ($algos as $algo) { | |
$ctx[$algo] = hash_init($algo); | |
} | |
// calculate hash | |
while (!feof($fp)) { | |
$buffer = fgets($fp, 65536); | |
foreach ($ctx as $key => $context) { | |
hash_update($ctx[$key], $buffer); | |
} | |
} | |
// finalise hash and store in return | |
foreach ($algos as $algo) { | |
$result[$algo] = hash_final($ctx[$algo]); | |
} | |
fclose($fp); | |
} else { | |
throw new \InvalidArgumentException('Could not open file for reading'); | |
} | |
return $result; | |
} | |
$result = hash_file_multi(['md5', 'sha1', 'sha256'], 'path/to/file.ext'); | |
var_dump($result['md5'] === hash_file('md5', 'path/to/file.ext')); //true | |
var_dump($result['sha1'] === hash_file('sha1', 'path/to/file.ext')); //true | |
var_dump($result['sha256'] === hash_file('sha256', 'path/to/file.ext')); //true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment