1. <?php
  2. /**
  3. * Hashes file contents with fallback logic.
  4. *
  5. * @param string $filePath The path to the file.
  6. * @param string $algorithm The hashing algorithm to use (md5, sha1, sha256, fallback). Defaults to sha256.
  7. * @return string|false The hash value, or false on failure.
  8. */
  9. function hashFileContents(string $filePath, string $algorithm = 'sha256'): string|false
  10. {
  11. if (!file_exists($filePath)) {
  12. return false; // File does not exist
  13. }
  14. $fileContent = file_get_contents($filePath);
  15. if ($fileContent === false) {
  16. return false; // Failed to read file
  17. }
  18. switch ($algorithm) {
  19. case 'md5':
  20. $hash = md5($fileContent);
  21. break;
  22. case 'sha1':
  23. $hash = sha1($fileContent);
  24. break;
  25. case 'sha256':
  26. $hash = hash('sha256', $fileContent);
  27. break;
  28. case 'fallback':
  29. //Try md5, then sha1, then sha256
  30. $hash = md5($fileContent);
  31. if ($hash === false) {
  32. $hash = sha1($fileContent);
  33. if ($hash === false) {
  34. $hash = hash('sha256', $fileContent);
  35. }
  36. }
  37. break;
  38. default:
  39. return false; // Invalid algorithm
  40. }
  41. return $hash;
  42. }
  43. //Example usage:
  44. // $hash = hashFileContents('my_file.txt', 'sha256');
  45. // if ($hash !== false) {
  46. // echo "Hash: " . $hash . "\n";
  47. // } else {
  48. // echo "Hashing failed.\n";
  49. // }
  50. ?>

Add your comment