1. <?php
  2. /**
  3. * Hashes metadata values with limited memory usage.
  4. *
  5. * This function iterates through the metadata values and hashes them
  6. * one at a time to avoid loading the entire dataset into memory.
  7. *
  8. * @param array $metadata An associative array of metadata values.
  9. * @param string $hash_algorithm The hashing algorithm to use (e.g., 'sha256', 'md5').
  10. * @return array An associative array where keys are the original metadata keys
  11. * and values are the corresponding hashes. Returns an empty array on error.
  12. */
  13. function hashMetadata(array $metadata, string $hash_algorithm = 'sha256'): array
  14. {
  15. $hashes = [];
  16. try {
  17. if (!function_exists($hash_algorithm)) {
  18. error_log("Hash algorithm '$hash_algorithm' not found.");
  19. return [];
  20. }
  21. foreach ($metadata as $key => $value) {
  22. if (is_string($value) || is_numeric($value)) { //only hash strings or numbers
  23. $hash = hash($hash_algorithm, $value);
  24. $hashes[$key] = $hash;
  25. } else {
  26. error_log("Skipping non-string/numeric value for key: " . $key);
  27. }
  28. }
  29. } catch (Exception $e) {
  30. error_log("Hashing error: " . $e->getMessage());
  31. return [];
  32. }
  33. return $hashes;
  34. }
  35. // Example usage:
  36. /*
  37. $metadata = [
  38. 'name' => 'Example Metadata',
  39. 'description' => 'This is an example description.',
  40. 'version' => 1.0,
  41. 'author' => 'John Doe',
  42. 'id' => 12345
  43. ];
  44. $hashes = hashMetadata($metadata, 'sha256');
  45. if ($hashes) {
  46. print_r($hashes);
  47. }
  48. */
  49. ?>

Add your comment