Created
April 9, 2018 11:40
-
-
Save teknikqa/af564d1d68619662c3cb2e45e6032662 to your computer and use it in GitHub Desktop.
Download helper to download files in chunks and save it
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 | |
| /** | |
| * @file | |
| * Download helper to download files in chunks and save it. | |
| * | |
| * @author Syed I.R | |
| * @author Modified by: Nick Mathew | |
| * @link https://github.com/irazasyed | |
| */ | |
| /** | |
| * Download files in chunks and save it. | |
| * | |
| * @param string $srcName | |
| * Source Path/URL to the file you want to download. | |
| * @param string $dstName | |
| * Destination Path to save your file. | |
| * @param int $chunkSize | |
| * (Optional) How many bytes to download per chunk (In MB). Defaults to 1 MB. | |
| * @param bool $returnbytes | |
| * (Optional) Return number of bytes saved. Default is TRUE. | |
| * | |
| * @return int | |
| * Returns number of bytes delivered. | |
| */ | |
| function download_file($srcName, $dstName, $chunkSize = 1, $returnbytes = TRUE) { | |
| // How many bytes per chunk. | |
| $chunksize = $chunkSize * (1024 * 1024); | |
| $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 number of bytes delivered like readfile() does. | |
| return $bytesCount; | |
| } | |
| return $status; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment