1. <?php
  2. /**
  3. * Attaches metadata to binary files for sandbox usage.
  4. *
  5. * @param string $filePath Path to the binary file.
  6. * @param array $metadata An associative array of metadata key-value pairs.
  7. * Example: ['author' => 'John Doe', 'date_created' => '2023-10-27']
  8. * @return bool True on success, false on failure.
  9. */
  10. function attachMetadataToBinaryFile(string $filePath, array $metadata): bool
  11. {
  12. if (!file_exists($filePath)) {
  13. error_log("File not found: $filePath");
  14. return false;
  15. }
  16. $metadataString = json_encode($metadata, JSON_PRETTY_PRINT); // Encode metadata to JSON
  17. if ($metadataString === false) {
  18. error_log("Failed to encode metadata to JSON: " . json_last_error_msg());
  19. return false;
  20. }
  21. $fileHandle = fopen($filePath, 'r+'); // Open file for reading and writing
  22. if ($fileHandle === false) {
  23. error_log("Failed to open file for reading/writing: $filePath");
  24. return false;
  25. }
  26. // Get the current file size
  27. $fileSize = filesize($filePath);
  28. // Write metadata to the beginning of the file
  29. $metadataLength = strlen($metadataString);
  30. if (fseek($fileHandle, 0, SEEK_SET) === -1) {
  31. fclose($fileHandle);
  32. error_log("Failed to seek to the beginning of the file: $filePath");
  33. return false;
  34. }
  35. if (fwrite($fileHandle, $metadataLength . "\n" . $metadataString . "\n") === false) {
  36. fclose($fileHandle);
  37. error_log("Failed to write metadata to file: $filePath");
  38. return false;
  39. }
  40. fclose($fileHandle);
  41. return true;
  42. }
  43. //Example usage
  44. /*
  45. $filePath = 'test.bin'; // Replace with your binary file path
  46. $metadata = [
  47. 'author' => 'Sandbox User',
  48. 'date_created' => date('Y-m-d H:i:s'),
  49. 'version' => '1.0'
  50. ];
  51. if (attachMetadataToBinaryFile($filePath, $metadata)) {
  52. echo "Metadata attached successfully to $filePath\n";
  53. } else {
  54. echo "Failed to attach metadata to $filePath\n";
  55. }
  56. */
  57. ?>

Add your comment