Skip to content

Instantly share code, notes, and snippets.

@DarkVss
Created July 11, 2023 14:43
Show Gist options
  • Save DarkVss/02bc7dd6c253e7b229edc50f6c62c64a to your computer and use it in GitHub Desktop.
Save DarkVss/02bc7dd6c253e7b229edc50f6c62c64a to your computer and use it in GitHub Desktop.
[PHP] Download/upload large file by chunks
<?php
const CHUNK_SIZE = 50 * 1024 * 1024;
function Download(string $url, string $filename) : bool {
$inputHandler = fopen($url, "r");
$fileHandler = fopen($filename, "w+");
if ($inputHandler === false || $fileHandler === false) {
return false;
}
while (true) {
$buffer = fgets($inputHandler, CHUNK_SIZE);
if (strlen($buffer) == 0) {
fclose($inputHandler);
fclose($fileHandler);
return true;
}
fwrite($fileHandler, $buffer);
}
}
function Upload(string $filename) : void {
$handle = fopen($filename, "rb");
if ($handle === false) {
return;
}
while (feof($handle) === false) {
echo fread($handle, CHUNK_SIZE);
ob_flush();
flush();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment