<?php
/**
* Attaches metadata to binary files for sandbox usage.
*
* @param string $filePath Path to the binary file.
* @param array $metadata An associative array of metadata key-value pairs.
* Example: ['author' => 'John Doe', 'date_created' => '2023-10-27']
* @return bool True on success, false on failure.
*/
function attachMetadataToBinaryFile(string $filePath, array $metadata): bool
{
if (!file_exists($filePath)) {
error_log("File not found: $filePath");
return false;
}
$metadataString = json_encode($metadata, JSON_PRETTY_PRINT); // Encode metadata to JSON
if ($metadataString === false) {
error_log("Failed to encode metadata to JSON: " . json_last_error_msg());
return false;
}
$fileHandle = fopen($filePath, 'r+'); // Open file for reading and writing
if ($fileHandle === false) {
error_log("Failed to open file for reading/writing: $filePath");
return false;
}
// Get the current file size
$fileSize = filesize($filePath);
// Write metadata to the beginning of the file
$metadataLength = strlen($metadataString);
if (fseek($fileHandle, 0, SEEK_SET) === -1) {
fclose($fileHandle);
error_log("Failed to seek to the beginning of the file: $filePath");
return false;
}
if (fwrite($fileHandle, $metadataLength . "\n" . $metadataString . "\n") === false) {
fclose($fileHandle);
error_log("Failed to write metadata to file: $filePath");
return false;
}
fclose($fileHandle);
return true;
}
//Example usage
/*
$filePath = 'test.bin'; // Replace with your binary file path
$metadata = [
'author' => 'Sandbox User',
'date_created' => date('Y-m-d H:i:s'),
'version' => '1.0'
];
if (attachMetadataToBinaryFile($filePath, $metadata)) {
echo "Metadata attached successfully to $filePath\n";
} else {
echo "Failed to attach metadata to $filePath\n";
}
*/
?>
Add your comment