-
-
Save muddy-28/a3ea46fb61176c87e3060700b4354db5 to your computer and use it in GitHub Desktop.
PHP: File downloader function - Downloading files in chunks.
This file contains hidden or 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 | |
/** | |
* Download helper to download files in chunks and save it. | |
* | |
* @author Syed I.R <[email protected]> | |
* @link https://github.com/irazasyed | |
* | |
* @param string $srcName Source Path/URL to the file you want to download | |
* @param string $dstName Destination Path to save your file | |
* @param integer $chunkSize (Optional) How many bytes to download per chunk (In MB). Defaults to 1 MB. | |
* @param boolean $returnbytes (Optional) Return number of bytes saved. Default: true | |
* | |
* @return integer Returns number of bytes delivered. | |
*/ | |
function downloadFile($srcName, $dstName, $chunkSize = 1, $returnbytes = true) { | |
$chunksize = $chunkSize*(1024*1024); // How many bytes per chunk | |
$data = ''; | |
$bytesCount = 0; | |
$handle = fopen($srcName, 'rb'); | |
$fp = fopen($dstName, 'w'); | |
if ($handle === false) { | |
return false; | |
} | |
while (!feof($handle)) { | |
$data = fread($handle, $chunksize); | |
fwrite($fp, $data, strlen($data)); | |
if ($returnbytes) { | |
$bytesCount += strlen($data); | |
} | |
} | |
$status = fclose($handle); | |
fclose($fp); | |
if ($returnbytes && $status) { | |
return $bytesCount; // Return number of bytes delivered like readfile() does. | |
} | |
return $status; | |
} | |
/** ------------------------------------------ | |
* Function Usage | |
* ------------------------------------------ | |
*/ | |
$bytes = downloadFile('http://wordpress.org/latest.zip', 'latest.zip'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment