1. <?php
  2. /**
  3. * Hashes entries with a timeout for dry-run scenarios.
  4. *
  5. * @param array $entries An array of entries to hash. Each entry should be a string.
  6. * @param string $hash_algorithm The hashing algorithm to use (e.g., 'md5', 'sha256').
  7. * @param int $timeout Timeout in seconds for each hash operation.
  8. * @return array An associative array where keys are the original entries and values are the hashes. Returns an empty array on error.
  9. */
  10. function hashEntriesWithTimeout(array $entries, string $hash_algorithm, int $timeout): array
  11. {
  12. $results = [];
  13. foreach ($entries as $entry) {
  14. try {
  15. if (strpos($hash_algorithm, 'sha') === 0) {
  16. $hash = hash_raw($hash_algorithm, $entry, true); // Use hash_raw for SHA algorithms
  17. } else {
  18. $hash = hash($hash_algorithm, $entry);
  19. }
  20. $results[$entry] = $hash;
  21. } catch (Exception $e) {
  22. // Handle potential errors, e.g., invalid hash algorithm.
  23. error_log("Error hashing entry '$entry': " . $e->getMessage());
  24. $results[$entry] = null; // Or some other error indicator.
  25. }
  26. }
  27. return $results;
  28. }
  29. // Example usage (dry-run scenario)
  30. $entries = ["entry1", "entry2", "entry3"];
  31. $hash_algorithm = "sha256";
  32. $timeout = 5; // seconds
  33. $hashed_entries = hashEntriesWithTimeout($entries, $hash_algorithm, $timeout);
  34. print_r($hashed_entries);
  35. ?>

Add your comment