1. <?php
  2. /**
  3. * Splits a binary file into chunks with retry logic.
  4. *
  5. * @param string $filePath Path to the binary file.
  6. * @param int $chunkSize Size of each chunk in bytes.
  7. * @param int $retries Number of retry attempts.
  8. * @return array Array of chunk data, or false on failure.
  9. */
  10. function splitBinaryFile(string $filePath, int $chunkSize, int $retries = 3): array|false
  11. {
  12. $fileLength = filesize($filePath);
  13. if ($fileLength <= 0) {
  14. return false; // File is empty or doesn't exist
  15. }
  16. $chunks = [];
  17. $start = 0;
  18. for ($i = 0; $i < $fileLength; $i += $chunkSize) {
  19. $end = min($start + $chunkSize, $fileLength);
  20. $chunk = file_get_contents($filePath, $start, $end - $start);
  21. if ($chunk === false) {
  22. $retries--;
  23. if ($retries > 0) {
  24. error_log("Failed to read chunk. Retrying... (attempt: $retries)");
  25. usleep(100000); // Wait 100ms before retrying
  26. continue;
  27. } else {
  28. error_log("Failed to read chunk after multiple retries.");
  29. return false; // Return false if all retries fail
  30. }
  31. }
  32. $chunks[] = $chunk;
  33. $start = $end;
  34. }
  35. return $chunks;
  36. }
  37. // Example usage:
  38. // $filePath = 'path/to/your/binary_file.bin';
  39. // $chunkSize = 1024 * 1024; // 1MB chunks
  40. // $chunks = splitBinaryFile($filePath, $chunkSize);
  41. // if ($chunks !== false) {
  42. // echo "File split into " . count($chunks) . " chunks.\n";
  43. // // Process the chunks here
  44. // foreach ($chunks as $index => $chunk) {
  45. // echo "Chunk " . ($index + 1) . " size: " . strlen($chunk) . "\n";
  46. // // Do something with $chunk
  47. // }
  48. // } else {
  49. // echo "Failed to split the file.\n";
  50. // }
  51. ?>

Add your comment