Skip to content

Instantly share code, notes, and snippets.

@nqphuong
Last active October 1, 2015 12:26
Show Gist options
  • Save nqphuong/bfff704993c03d57dbab to your computer and use it in GitHub Desktop.
Save nqphuong/bfff704993c03d57dbab to your computer and use it in GitHub Desktop.
<?php
/*
$root: Path to your file
$filename: Name of file to read
$ext: Your file extension
*/
private function download_big_text_file ($root, $filename, $ext) {
//Max file size
$max_file_size = 10*1024*1024;
//Calculate file size
$filesize = filesize($root.$filename.$ext);
//Determine a number of file to divide
$num = intval($filesize / $max_file_size) + ((($filesize % $max_file_size) == 0) ? 0 : 1);
$buffer = '';
//Open file
$handle = fopen($root.$filename.$ext, 'rb');
if ($handle === false) {
return false;
}
//Create zip package to store all files divided
$zip = new ZipArchive;
$zipname = "{$filename}.zip";
//Delete file if exists
if(file_exists($root.$zipname)){
unlink($root.$zipname);
}
//Create zip package
if(!$zip->open($root.$zipname, ZIPARCHIVE::CREATE)){
echo 'Could not open archive<br />';
return;
}
//Read big file and insert in zip file
$num -= 1;
$total = 0;
for($i = 0; $i < $num; $i++){
//Create new file content with WRITE mode. Ex: example_p1.txt
$newfile = "{$root}{$filename}_p$i{$ext}";
$fnewfile = fopen($newfile, 'w');
//Copy data by MAX_FILE_SIZE
stream_copy_to_stream($handle, $fnewfile, $max_file_size);
//Push to zip
$zip->addFile($newfile, "{$filename}_p$i{$ext}");
}
//Repeat for the last file
$newfile = "{$root}{$filename}_p$num{$ext}";
$fnewfile = fopen($newfile, 'w');
stream_copy_to_stream($handle, $fnewfile, $max_file_size);
$zip->addFile($newfile, "{$filename}_p$num{$ext}");
//Close zip handler
$zip->close();
fclose($handle);
//-----------------
//Download zip file
//-----------------
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-Type: text/html; charset=UTF-8');
header("Content-Disposition: attachment; filename={$filename}.zip");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
$this->readfile_chunked($root, $zipname);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment