You are here: Re: displaying a file not in the webroot « PHP Programming Language « IT news, forums, messages
Re: displaying a file not in the webroot

Posted by Good Man on 01/11/08 16:39

firewoodtim@yahoo.com wrote in news:8p5fo3dfmas4c1631shr2onc7jp991dph6@
4ax.com:

> I want to display an uploaded file (e.g. a pdf file) in a "_blank"
> target window. The file is stored outside of the webroot at
> "/home/myhome/uploads/" and was uploaded by a trusted user with the
> function, move_uploaded_file().
>
> I've checked out readfile(), but there is scant info in the way of
> examples on php.net. Can anyone help with some code?
>

I use a custom function called "readfile_chunked" (on the 'readfile'
manual page) because I've had bad luck with downloads stoppping at
2MB... here are the nuts and bolts of my "streamFile.php":

<?php

header("Cache-control: private");

//we stream the file, prompting a download
header('Content-Type: application/octet-stream');

// It will be called whatever we want (ie: "MyFile.pdf")
$theFileName = "MyFile.pdf";
header('Content-Disposition: attachment; filename="'.$theFileName.'"');

//this custom function is a good one for streaming files to browsers;
//it does not suffer from a 2MB limit like "readfile();" sometimes does

$thePathToTheFile = "/home/myhome/uploads/superDuper.pdf";
readfile_chunked($thePathToTheFile);

//and here is that handy-dandy function
function readfile_chunked($filename,$retbytes=true) {
$chunksize = 1*(1024*1024); // how many bytes per chunk
$buffer = '';
$cnt =0;
// $handle = fopen($filename, 'rb');
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
echo $buffer;
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;

}

?>

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация