Skip to content

Instantly share code, notes, and snippets.

@teknikqa
Forked from irazasyed/downloadFileChunks.php
Last active November 3, 2015 12:46
Show Gist options
  • Save teknikqa/ad0940587034b80502a6 to your computer and use it in GitHub Desktop.
Save teknikqa/ad0940587034b80502a6 to your computer and use it in GitHub Desktop.
PHP: File downloader function - Downloading files in chunks.
<?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