1. <?php
  2. /**
  3. * Imports data from a binary file in chunks to manage memory usage.
  4. *
  5. * @param string $filePath Path to the binary file.
  6. * @param callable $callback A callback function to process each chunk of data.
  7. * The callback function receives the chunk as a string.
  8. * @param int $chunkSize The size of each chunk in bytes. Default is 4096.
  9. * @return bool True on success, false on failure.
  10. */
  11. function importBinaryFileInChunks(string $filePath, callable $callback, int $chunkSize = 4096): bool
  12. {
  13. if (!file_exists($filePath)) {
  14. error_log("File not found: " . $filePath);
  15. return false;
  16. }
  17. $fileHandle = fopen($filePath, 'rb'); // Open the file in binary read mode.
  18. if ($fileHandle === false) {
  19. error_log("Failed to open file: " . $filePath);
  20. return false;
  21. }
  22. $buffer = '';
  23. while (!feof($fileHandle)) {
  24. $chunk = fread($fileHandle, $chunkSize); // Read a chunk of data.
  25. if ($chunk === false) {
  26. $error = error_get_last();
  27. error_log("Error reading file: " . $error['message']);
  28. fclose($fileHandle);
  29. return false;
  30. }
  31. $buffer .= $chunk; // Append the chunk to the buffer.
  32. // Process the chunk using the callback function.
  33. $callback($buffer);
  34. $buffer = ''; // Clear the buffer.
  35. }
  36. fclose($fileHandle); // Close the file handle.
  37. return true;
  38. }
  39. //Example usage:
  40. /*
  41. function processChunk(string $chunk): void{
  42. //Do something with the chunk of data
  43. echo "Processing chunk of size: " . strlen($chunk) . "\n";
  44. }
  45. if (importBinaryFileInChunks('large_binary_file.bin', 'processChunk', 1024)) {
  46. echo "File imported successfully.\n";
  47. } else {
  48. echo "File import failed.\n";
  49. }
  50. */
  51. ?>

Add your comment