There's a question here (on StackOverflow) that asks about streaming large files to user in chunks. A referred to code, originally here, in an answer to this question tells how. I'm looking for how to just save the file to server.
Notes:
- The script here aims to download a file to server by providing URL to download file from (This process is also named remote upload).
- My server provider disabled me from editing time limit, so downloads using this script takes time.
- I am able to save file contents to server using
file_put_contents("MyFile.iso",$buffer,FILE_APPEND)
, but not the whole file, mostly because the script takes long time running so it times out. - I think a solution may work like so: a JavaScript method requests PHP actions in the background via AJAX multiple times, the first background request tells PHP to download the first 100MB of the file. The second request tells PHP to download the second 100MB of the file, and so on till the PHP tells Javascript that we reached to the end of the file. So instead we downloaded the file in one whole process (long time taking), we downloaded it on multiple processes (small time taking).
- A good start: How to partially download a remote file with cURL? (I will find time later soon to develop the whole solution altogether. Any help will be appreciated.
Below is the mentioned code that I need to start with in order to save/remote-upload file to server: (edited: it now saves the file to server, but not the whole file, mostly because the script takes long time running)
<?php
define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of tiles chunk
// Read a file and display its content chunk by chunk
function readfile_chunked($fileurl, $retbytes = TRUE) {
$buffer = '';
$cnt = 0;
$handle = fopen($fileurl, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, CHUNK_SIZE);
file_put_contents("MyFile.iso",$buffer,FILE_APPEND);
ob_flush();
flush();
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
$fileurl = 'http://releases.ubuntu.com/16.04.2/ubuntu-16.04.2-desktop-amd64.iso';
$mimetype = 'mime/type';
header('Content-Type: '.$mimetype );
readfile_chunked($fileurl);
?>