<?php
/**
* Hashes file contents with fallback logic.
*
* @param string $filePath The path to the file.
* @param string $algorithm The hashing algorithm to use (md5, sha1, sha256, fallback). Defaults to sha256.
* @return string|false The hash value, or false on failure.
*/
function hashFileContents(string $filePath, string $algorithm = 'sha256'): string|false
{
if (!file_exists($filePath)) {
return false; // File does not exist
}
$fileContent = file_get_contents($filePath);
if ($fileContent === false) {
return false; // Failed to read file
}
switch ($algorithm) {
case 'md5':
$hash = md5($fileContent);
break;
case 'sha1':
$hash = sha1($fileContent);
break;
case 'sha256':
$hash = hash('sha256', $fileContent);
break;
case 'fallback':
//Try md5, then sha1, then sha256
$hash = md5($fileContent);
if ($hash === false) {
$hash = sha1($fileContent);
if ($hash === false) {
$hash = hash('sha256', $fileContent);
}
}
break;
default:
return false; // Invalid algorithm
}
return $hash;
}
//Example usage:
// $hash = hashFileContents('my_file.txt', 'sha256');
// if ($hash !== false) {
// echo "Hash: " . $hash . "\n";
// } else {
// echo "Hashing failed.\n";
// }
?>
Add your comment