1. <?php
  2. /**
  3. * Serializes binary file objects for internal tooling.
  4. * Uses synchronous execution.
  5. *
  6. * @param mixed $object The object to serialize. Assumed to be a file handle/resource.
  7. * @param string $output_path The path to write the serialized data.
  8. * @return bool True on success, false on failure.
  9. */
  10. function serializeBinaryFile(mixed $object, string $output_path): bool
  11. {
  12. try {
  13. $file_content = fread($object, filesize($object)); // Read the entire file content
  14. if ($file_content === false) {
  15. return false; // Error reading the file
  16. }
  17. $serialized_data = serialize($file_content); // Serialize the file content
  18. if ($serialized_data === false) {
  19. return false; // Error during serialization
  20. }
  21. if (file_put_contents($output_path, $serialized_data) === false) {
  22. return false; // Error writing to the output file
  23. }
  24. return true; // Success
  25. } catch (Exception $e) {
  26. // Handle exceptions, log them, or return false.
  27. error_log("Error serializing binary file: " . $e->getMessage());
  28. return false;
  29. }
  30. }
  31. //Example Usage (replace with your file handle/resource and output path)
  32. /*
  33. $file_handle = fopen('path/to/your/binary_file.bin', 'rb');
  34. if ($file_handle) {
  35. $success = serializeBinaryFile($file_handle, 'path/to/output/serialized_file.txt');
  36. fclose($file_handle);
  37. if ($success) {
  38. echo "File serialized successfully.\n";
  39. } else {
  40. echo "File serialization failed.\n";
  41. }
  42. } else {
  43. echo "Could not open the input file.\n";
  44. }
  45. */
  46. ?>

Add your comment