<?php
/**
* Hashes metadata values with limited memory usage.
*
* This function iterates through the metadata values and hashes them
* one at a time to avoid loading the entire dataset into memory.
*
* @param array $metadata An associative array of metadata values.
* @param string $hash_algorithm The hashing algorithm to use (e.g., 'sha256', 'md5').
* @return array An associative array where keys are the original metadata keys
* and values are the corresponding hashes. Returns an empty array on error.
*/
function hashMetadata(array $metadata, string $hash_algorithm = 'sha256'): array
{
$hashes = [];
try {
if (!function_exists($hash_algorithm)) {
error_log("Hash algorithm '$hash_algorithm' not found.");
return [];
}
foreach ($metadata as $key => $value) {
if (is_string($value) || is_numeric($value)) { //only hash strings or numbers
$hash = hash($hash_algorithm, $value);
$hashes[$key] = $hash;
} else {
error_log("Skipping non-string/numeric value for key: " . $key);
}
}
} catch (Exception $e) {
error_log("Hashing error: " . $e->getMessage());
return [];
}
return $hashes;
}
// Example usage:
/*
$metadata = [
'name' => 'Example Metadata',
'description' => 'This is an example description.',
'version' => 1.0,
'author' => 'John Doe',
'id' => 12345
];
$hashes = hashMetadata($metadata, 'sha256');
if ($hashes) {
print_r($hashes);
}
*/
?>
Add your comment