Tuesday, 17 September 2013

Processing php code after readfile()

Processing php code after readfile()

I'm trying to wrap my head around processing of headers and readfile(). It
appears that no code is executed after readfile() is called. I presume
because of the "One HTTP Request, one file" rule.
I read a suggestion of using an iframe to perhaps get around this
limitation. I've tried putting this function in a separate file (e.g.
writezip) and calling it from a another file like:
<? echo '<iframe src="writezip.php">' ?>
echo "File was sent to you";
But this doesn't appear to work. Any suggestions? How would you display a
message saying "A file was sent" - Thanks in advance
<?php
function writezip(){
$fullfilename = "post.zip";
$outfilename = "test.zip";
$mode = "download";
if (file_exists($fullfilename)){
// Parse Info / Get Extension
$fsize = filesize($fullfilename);
$path_parts = pathinfo($fullfilename);
$ext = strtolower($path_parts["extension"]);
// Determine Content Type
switch ($ext) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain
browsers
header("Content-Type: $ctype");
$outfilename = ($outfilename=="" ? basename($fullfilename) :
$outfilename);
if ($mode == "view"){
// View file
header('Content-Disposition: inline; filename='.$outfilename);
}
else {
// Download file
header('Content-Disposition: attachment;
filename='.basename($outfilename));
}
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
if (ob_get_length() > 0 ) {
ob_clean();
flush();
}
readfile( $fullfilename );
die("anything here");
}
else
{
echo "File not found: ". $fullfilename;
}
}
?>

No comments:

Post a Comment