Created
July 11, 2023 14:43
-
-
Save DarkVss/02bc7dd6c253e7b229edc50f6c62c64a to your computer and use it in GitHub Desktop.
[PHP] Download/upload large file by chunks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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