<?php
/**
* Splits a binary file into chunks with retry logic.
*
* @param string $filePath Path to the binary file.
* @param int $chunkSize Size of each chunk in bytes.
* @param int $retries Number of retry attempts.
* @return array Array of chunk data, or false on failure.
*/
function splitBinaryFile(string $filePath, int $chunkSize, int $retries = 3): array|false
{
$fileLength = filesize($filePath);
if ($fileLength <= 0) {
return false; // File is empty or doesn't exist
}
$chunks = [];
$start = 0;
for ($i = 0; $i < $fileLength; $i += $chunkSize) {
$end = min($start + $chunkSize, $fileLength);
$chunk = file_get_contents($filePath, $start, $end - $start);
if ($chunk === false) {
$retries--;
if ($retries > 0) {
error_log("Failed to read chunk. Retrying... (attempt: $retries)");
usleep(100000); // Wait 100ms before retrying
continue;
} else {
error_log("Failed to read chunk after multiple retries.");
return false; // Return false if all retries fail
}
}
$chunks[] = $chunk;
$start = $end;
}
return $chunks;
}
// Example usage:
// $filePath = 'path/to/your/binary_file.bin';
// $chunkSize = 1024 * 1024; // 1MB chunks
// $chunks = splitBinaryFile($filePath, $chunkSize);
// if ($chunks !== false) {
// echo "File split into " . count($chunks) . " chunks.\n";
// // Process the chunks here
// foreach ($chunks as $index => $chunk) {
// echo "Chunk " . ($index + 1) . " size: " . strlen($chunk) . "\n";
// // Do something with $chunk
// }
// } else {
// echo "Failed to split the file.\n";
// }
?>
Add your comment