UBB.Dev
I am using a script like given below to open files stored *outside* the webroot directory for users to download. The problem is whenever the filesize exceeds 400,000 bytes, this script cannot open the file. It returns a blank page

Any idea what I shall do to get rid of this??


<?
define('FILEDIR', '/home/myhotboard.com/downloads/');
//storage directory outside the root
$path = FILEDIR . $file;

$mimetype = array(
'doc'=>'application/msword',
'htm'=>'text/html',
'html'=>'text/html',
'jpg'=>'image/jpeg',
'pdf'=>'application/pdf',
'txt'=>'text/plain',
'xls'=>'application/vnd.ms-excel'
);

$p = explode('.', $file);
$pc = count($p);



header("Content-type: application/force-download\n");
header("Content-disposition: attachment; filename="$file"\n");
header("Content-transfer-encoding: binary\n");
header("Content-length: " . filesize($path) . "\n");

//send file contents
$fp=fopen($path, "r");
fpassthru($fp);
?>
One thing I would change is to use a loop, rather than reading the whole file into memory, as fpassthru probably does:

Code
//send file contents <br />(($fp = fopen($path, 'rb')) !== FALSE) or die("fopen: failed to open '$file'\n"); <br />while (!feof($fp)) { <br />   $buf = fread($fp, 16384); <br />   fwrite($fp, $buf); <br />} <br />fclose($fp);


The buffer size of 16384 (16K) is arbitrary. You could make it larger or smaller.

It's also a good idea to use the 'b' (binary) flag as above, so that the script will work on both Unix and Windows platforms.
So the final code shall look like?


//send file contents
$fp=fopen($path, "rb");
(($fp = fopen($path, 'rb')) !== FALSE) or die("fopen: failed to open '$file'\n");
while (!feof($fp)) {
$buf = fread($fp, 32768);
fwrite($fp, $buf);
}
fpassthru($fp);
fclose($fp);
?>

The code I posted would replace your code, so it should look like:

Code
//send file contents<br />(($fp = fopen($path, 'rb')) !== FALSE) or die("fopen: failed to open '$file'\n");<br />while (!feof($fp)) {<br />   $buf = fread($fp, 32768);<br />   fwrite($fp, $buf);<br />}<br />fclose($fp);<br />?>

© UBB.Developers