php download file as stream using readfile() function


here is how to download file using readfile() in php as a stream, this way also works if your normal readfile return empty file, or when your readfile return broken file.

// give file to download
download(“/path/to/your/file.zip”);

/**
* Download file
*
* @param string $path
* @param string $type
* @param string $name
* @param bool $force_download
* @return bool
*/
function download($path, $name = ”, $type = ‘application/octet-stream’, $force_download = true) {

if (!is_file($path) || connection_status() !== 0);

if($force_download) {
header(“Cache-Control: public”);
} else {
header(“Cache-Control: no-store, no-cache, must-revalidate”);
header(“Cache-Control: post-check=0, pre-check=0”, false);
header(“Pragma: no-cache”);
}

header(“Expires: “.gmdate(“D, d M Y H:i:s”, mktime(date(“H”)+2, date(“i”), date(“s”), date(“m”), date(“d”), date(“Y”))).” GMT”);
header(“Last-Modified: “.gmdate(“D, d M Y H:i:s”).” GMT”);
header(“Content-Type: $type”);
header(“Content-Length: “.(string)(filesize($path)));

$disposition = $force_download ? ‘attachment’ : ‘inline’;

if(trim($name) == ”) {
header(“Content-Disposition: $disposition; filename=” . basename($path));
} else {
header(“Content-Disposition: $disposition; filename=\”” . trim($name).”\””);
}

header(“Content-Transfer-Encoding: binary\n”);

if ($file = fopen($path, ‘rb’)) {
while(!feof($file) and (connection_status()==0)) {
print(fread($file, 1024*8));
flush();
}
fclose($file);
}

return((connection_status() == 0) && !connection_aborted());
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s