I used this script to limit number of downloads but the downloaded zip files become corrupt.
This is the code can anyone debug this script

$path ="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
//addslashes($_SERVER['REQUEST_URI']);
$ip = addslashes($_SERVER['REMOTE_ADDR']);
$dl = false;


$sql = sprintf("SELECT UNIX_TIMESTAMP(last_access) last_time FROM downloaded WHERE filepath = '%s' AND ipadres = '%s' ORDER BY last_access DESC", $path, $ip);
$res = mysql_query($sql);
if (mysql_num_rows($res) > 0) {
$last_xs = mysql_result($res, 0, 'last_time')+3600;
if ($last_xs < time()) {
mysql_query(sprintf("REPLACE downloaded SET filepath = '%s', ipadres = '%s', last_access = NOW()", $path, $ip));
$dl = true;
}
} else {
$sql = sprintf("REPLACE downloaded SET filepath = '%s', ipadres = '%s', last_access = NOW()", $path, $ip);
mysql_query($sql);
$dl = true;
}
echo"<br> here is : ".$path."<br>";

if ($dl) {
$fullPath = $_SERVER['DOCUMENT_ROOT'].$path;
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
//$chunksize = 1*(1024*1024);
if ($fd = fopen ($path, "r")) {
$fname = basename($path);
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length: ".filesize($path));
header("Content-Disposition: attachment; filename=\"".basename($fname)."\"");
header("Content-Description: File Transfer");
//header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
//header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: private");
header("Accept-Ranges: bytes");
header('Vary: User-Agent');

while(!feof($fd)) {
//$buffer = fread($fd,500*1024);
$buffer = fread($fd,filesize($path));
//$buffer = readfile($fd);
//$buffer = fread($fd, $chunksize);
//$buffer = fread($fd, (1*(1024*1024)));
//$buffer = file_get_contents($fd);
echo $buffer;
//ob_flush();
ob_end_flush();

}
fclose ($fd);
exit;
}
} else {
header('HTTP/1.0 503 Service Unavailable');
die('Abort, You reached your download limit for this file.');
}
?>

I tried several options as shown with //
Inputs by you all will be extremely helpful.