Hi, wasn't sure where to put this. However since I used PHP in my download script, felt it was appropriate to ask here.

Anyway my problem is pretty easy to describe, any downloaded zips off my website are corrupted (however are fine before being uploaded).

Is there a way to diagnose what the problem is?


Thanks.

You are uploading/downloading via script. Maybe when downloading the zip, the php header is not set correctly. Did you try downloading the zip directly (not through a script) ?

Yes it works fine without the PHP, and it usually works fine using the script way too. However this script was working fine before, the only changes I made were to how it found the file on my webspace (I integrated the use of the database to find the files). So I really have no idea what is wrong with it :/ Should I post the script?

<?php

if(DB_IsDownloadsEnabled() != true)
{
	REDIRERROR("Downloads are currently disabled, please try again later");
	exit(0);
}

$idx = -1;
$file1 = "";
$file2 = "";
if(isset($_GET[FILEDL_ID]))
{
	$idx = intval($_GET[FILEDL_ID]);
	$hMySQL = mysql_connect(DB_URL, DB_USERNAME, DB_PASS);
	
	if($hMySQL)
	{
		if(mysql_select_db(DB_NAME, $hMySQL))
		{
			
			$query = "SELECT * FROM " . DB_TNAME_DOWNLOAD. " WHERE " . DB_T_DOWNLOAD_ID . "='$idx'";			
			$result = (mysql_query($query, $hMySQL));
			
			//if(!$result) { REDIRERROR("Error accessing my square lady: " . mysql_error($result));}
			
			mysql_close($hMySQL);
			if(mysql_num_rows($result) == 0)
			{
				REDIRERROR("Error, download does not exist.<br>" . mysql_num_rows($result));
			}
			else
			{
				if(mysql_result($result, 0, DB_T_DOWNLOAD_ENABLED) != 0)
				{
					$file1 = mysql_result($result, 0, DB_T_DOWNLOAD_FILENAME);
					$file2 = mysql_result($result, 0, DB_T_DOWNLOAD_FILENAME2);
				}
				else
				{
					REDIRERROR("Error, download does not exist!"); //deny access
				}
			}		

		}
		else
		{
			mysql_close($hMySQL);
			REDIRERROR("Error with my square lady!<br>".mysql_error($hMySQL));
		}
	}
	else
	{
		REDIRERROR("Error, could not connect to my square lady");
	}
}
else
{
	REDIRERROR("Download ID not set!"); //REMEMBER TO CREATE REDIRECT SCRIPT TO REDIRECT TO MAIN PAGE WITH AN ERROR MESSAGE (ADD TO SWITCH TO DISPLAY THAT PAGE)
}


$_GET['f'] = $file1; //stored on server with this filename
$_GET['fc'] = $file2; //will save as this name
//I decided to do this so that it is harder to attach to the files by hotlinking, should the downloads folder be discovered =]




###############################################################
# File Download 1.3
###############################################################
# Visit http://www.zubrag.com/scripts/ for updates
###############################################################
# Sample call:
#    download.php?f=phptutorial.zip
#
# Sample call (browser will try to save with new file name):
#    download.php?f=phptutorial.zip&fc=php123tutorial.zip
###############################################################

// Allow direct file download (hotlinking)?
// Empty - allow hotlinking
// If set to nonempty value (Example: example.com) will only allow downloads when referrer contains this text
define('ALLOWED_REFERRER', "dmkp.wildman-productions.org");

define('ALLOWED_REFERRER_2', "popre.net");

// Download folder, i.e. folder where you keep all files for download.
// MUST end with slash (i.e. "/" )
define('BASE_DIR',$_SERVER['DOCUMENT_ROOT'].'/__file__downloads/');

// log downloads?  true/false
define('LOG_DOWNLOADS',true);

// log file name
define('LOG_FILE','downloads.log');

// Allowed extensions list in format 'extension' => 'mime type'
// If myme type is set to empty string then script will try to detect mime type 
// itself, which would only work if you have Mimetype or Fileinfo extensions
// installed on server.
$allowed_ext = array (

  // archives
  'zip' => 'application/zip',

  // documents
  'pdf' => 'application/pdf',
  'doc' => 'application/msword',
  'xls' => 'application/vnd.ms-excel',
  'ppt' => 'application/vnd.ms-powerpoint',
  
  // executables
  'exe' => 'application/octet-stream',

  // images
  'gif' => 'image/gif',
  'png' => 'image/png',
  'jpg' => 'image/jpeg',
  'jpeg' => 'image/jpeg',

  // audio
  'mp3' => 'audio/mpeg',
  'wav' => 'audio/x-wav',

  // video
  'mpeg' => 'video/mpeg',
  'mpg' => 'video/mpeg',
  'mpe' => 'video/mpeg',
  'mov' => 'video/quicktime',
  'avi' => 'video/x-msvideo'
);



####################################################################
###  DO NOT CHANGE BELOW
####################################################################

// If hotlinking not allowed then make hackers think there are some server problems
if ((ALLOWED_REFERRER !== '') && (isset($_SERVER['HTTP_REFERER'])))
{
	if((strpos(strtoupper($_SERVER['HTTP_REFERER']),strtoupper(ALLOWED_REFERRER)) === false) && (strpos(strtoupper($_SERVER['HTTP_REFERER']),strtoupper(ALLOWED_REFERRER_2)) === false))
	{
  		REDIRERROR("Internal server error. Please contact system administrator.");
  	}
}
//echo($_SERVER['HTTP_REFERER'] . "<br>" . ALLOWED_REFERRER . "<br>" . ALLOWED_REFERRER_2);
//die("<br>End of test");



// Make sure program execution doesn't time out
// Set maximum script execution time in seconds (0 means no limit)
set_time_limit(0);

if (!isset($_GET['f']) || empty($_GET['f'])) {
  //REDIRERROR("Please specify file name for download.");
  REDIRERROR("Invalid download");
}

// Get real file name.
// Remove any path info to avoid hacking by adding relative path, etc.
$fname = basename($_GET['f']);

// Check if the file exists
// Check in subfolders too
function find_file ($dirname, $fname, &$file_path) {

  $dir = opendir($dirname);

  while ($file = readdir($dir)) {
    if (empty($file_path) && $file != '.' && $file != '..') {
      if (is_dir($dirname.'/'.$file)) {
        find_file($dirname.'/'.$file, $fname, $file_path);
      }
      else {
        if (file_exists($dirname.'/'.$fname)) {
          $file_path = $dirname.'/'.$fname;
          return;
        }
      }
    }
  }

} // find_file

// get full file path (including subfolders)
$file_path = '';
find_file(BASE_DIR, $fname, $file_path);

if (!is_file($file_path)) {
  REDIRERROR("File does not exist. Make sure you specified correct file name."); 
}

// file size in bytes
$fsize = filesize($file_path); 

// file extension
$fext = strtolower(substr(strrchr($fname,"."),1));

// check if allowed extension
if (!array_key_exists($fext, $allowed_ext)) {
  REDIRERROR("Not allowed file type."); 
}

// get mime type
if ($allowed_ext[$fext] == '') {
  $mtype = '';
  // mime type is not set, get from server settings
  if (function_exists('mime_content_type')) {
    $mtype = mime_content_type($file_path);
  }
  else if (function_exists('finfo_file')) {
    $finfo = finfo_open(FILEINFO_MIME); // return mime type
    $mtype = finfo_file($finfo, $file_path);
    finfo_close($finfo);  
  }
  if ($mtype == '') {
    $mtype = "application/force-download";
  }
}
else {
  // get mime type defined by admin
  $mtype = $allowed_ext[$fext];
}

// Browser will try to save file with this filename, regardless original filename.
// You can override it if needed.

if (!isset($_GET['fc']) || empty($_GET['fc'])) {
  $asfname = $fname;
}
else {
  // remove some bad chars
  $asfname = str_replace(array('"',"'",'\\','/'), '', $_GET['fc']);
  if ($asfname === '') $asfname = 'NoName';
}

// set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mtype");
header("Content-Disposition: attachment; filename=\"$asfname\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);

// download
// @readfile($file_path);
$file = @fopen($file_path,"rb");
if ($file) {
  while(!feof($file)) {
    print(fread($file, 1024*8));
    flush();
    if (connection_status()!=0) {
      @fclose($file);
      REDIRERROR("Unknown error");
    }
  }
  @fclose($file);
}

// log downloads
//if (!LOG_DOWNLOADS) REDIRERROR("Enjoy your download");


//get ip of visitor
if ($_SERVER['HTTP_X_FORWARD_FOR']) {
	$ipv4 = $_SERVER['HTTP_X_FORWARD_FOR'];
} else {
	$ipv4 = $_SERVER['REMOTE_ADDR'];
}

if(!AddDownloadLog(intval($idx), strval($ipv4), intval(time())))
{
	$f = @fopen(LOG_FILE, 'a+');
	if ($f) {
  	@fputs($f, date("m.d.Y g:ia")."  ".$_SERVER['REMOTE_ADDR']."  ".$fname."\r\n");
  	@fclose($f);
	}
}
				$counted = false; //has it been added to db?
				$query = "SELECT * FROM " . DB_TNAME_DOWNLOAD . " WHERE " . DB_T_DOWNLOAD_ID . "='$idx'"; //initial query
				$hMySQL = mysql_connect(DB_URL, DB_USERNAME, DB_PASS); //connect
				if($hMySQL) //is it connected?
				{
					//increment download count
					
					if(mysql_select_db(DB_NAME, $hMySQL)) //select db
					{
						$result = mysql_query($query); //query
						if(mysql_num_rows($result) == 1)
						{
							$count = mysql_result($result, 0, DB_T_DOWNLOAD_NUMDOWNLOADED); //get count var
							$count += 1; //increment
							
							$query = "UPDATE " . DB_TNAME_DOWNLOAD . " SET " . DB_T_DOWNLOAD_NUMDOWNLOADED . "='$count' WHERE ". DB_T_DOWNLOAD_ID . "='$idx'";
							//new query
							if(mysql_query($query))
							{
								$counted = true;
							}
						}
						
						mysql_close($hMySQL);
					}
				}

				if($counted == false) //was it added to db? if not then add to file for later manual adding
				{
						$f = @fopen(LOG_FILE, 'a+');
						if ($f) {
  						@fputs($f, $idx." is downloaded and not incremented in the db\r\n");
  						@fclose($f);
						}
				} //append to file

REDIRERROR("Enjoy your download");
?>

appears okay, i'm stumped. when i get back home i'll see if i get it to run. Hopefully someone else can help you before that.

Any idea yet?

Check the file size that is downloaded. If it is 0Kb then you will find that your script is not specifying the correct location. Other than that I don't have a clue as the syntax used in your code is a bit hard to read.

Yeah the file size is the same 0.o.

I didn't write the download script itself, only the database stuff. Download script is between line 66 and 266.

I have just checked your script and it appears your script is fine but looks more like if the entries in your database are not. Make sure the file locations in the database match the file locations in the file system. So in your script the downloads will be performed in www.yoursite.com/folder_script_is_in/__file__downloads/filename.zip

Hmm I don't understand... it does download the files, and the sizes are the correct size, the only problem being they end up as corrupted zip files 0.o

First to make this easier to understand it is the following section of the script that actually transfers the files as the download headers have just been set in that section:

// set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mtype");
header("Content-Disposition: attachment; filename=\"$asfname\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);
 
// download
// @readfile($file_path);
$file = @fopen($file_path,"rb");
if ($file) {
  while(!feof($file)) {
    print(fread($file, 1024*8));
    flush();
    if (connection_status()!=0) {
      @fclose($file);
      REDIRERROR("Unknown error");
    }
  }
  @fclose($file);
}
 
// log downloads
//if (!LOG_DOWNLOADS) REDIRERROR("Enjoy your download");
 
 
//get ip of visitor
if ($_SERVER['HTTP_X_FORWARD_FOR']) {
	$ipv4 = $_SERVER['HTTP_X_FORWARD_FOR'];
} else {
	$ipv4 = $_SERVER['REMOTE_ADDR'];
}
 
if(!AddDownloadLog(intval($idx), strval($ipv4), intval(time())))
{
	$f = @fopen(LOG_FILE, 'a+');
	if ($f) {
  	@fputs($f, date("m.d.Y g:ia")."  ".$_SERVER['REMOTE_ADDR']."  ".$fname."\r\n");
  	@fclose($f);
	}
}
				$counted = false; //has it been added to db?
				$query = "SELECT * FROM " . DB_TNAME_DOWNLOAD . " WHERE " . DB_T_DOWNLOAD_ID . "='$idx'"; //initial query
				$hMySQL = mysql_connect(DB_URL, DB_USERNAME, DB_PASS); //connect
				if($hMySQL) //is it connected?
				{
					//increment download count
 
					if(mysql_select_db(DB_NAME, $hMySQL)) //select db
					{
						$result = mysql_query($query); //query
						if(mysql_num_rows($result) == 1)
						{
							$count = mysql_result($result, 0, DB_T_DOWNLOAD_NUMDOWNLOADED); //get count var
							$count += 1; //increment
 
							$query = "UPDATE " . DB_TNAME_DOWNLOAD . " SET " . DB_T_DOWNLOAD_NUMDOWNLOADED . "='$count' WHERE ". DB_T_DOWNLOAD_ID . "='$idx'";
							//new query
							if(mysql_query($query))
							{
								$counted = true;
							}
						}
 
						mysql_close($hMySQL);
					}
				}
 
				if($counted == false) //was it added to db? if not then add to file for later manual adding
				{
						$f = @fopen(LOG_FILE, 'a+');
						if ($f) {
  						@fputs($f, $idx." is downloaded and not incremented in the db\r\n");
  						@fclose($f);
						}
				} //append to file
 
REDIRERROR("Enjoy your download");

And after checking that script I now kinda understand why it is corrupted. The last header seems to set the filesize so even if no file is specified it still needs to download blank zeros as binary. And after the headers have been set, I cannot see any section of the script that forces the download to happen. Perhaps the zip files that are download are only blank binary files that only contain zeros.

So has this script been download from another website or did you write this yourself. If you did download it from another website and just add the database functions then could you post the original script to compare. Or if the script is entirely your work then you will probably need to add a file retrieve function.

Here is the original.

<?php

###############################################################
# File Download 1.3
###############################################################
# Visit http://www.zubrag.com/scripts/ for updates
###############################################################
# Sample call:
#    download.php?f=phptutorial.zip
#
# Sample call (browser will try to save with new file name):
#    download.php?f=phptutorial.zip&fc=php123tutorial.zip
###############################################################

// Allow direct file download (hotlinking)?
// Empty - allow hotlinking
// If set to nonempty value (Example: example.com) will only allow downloads when referrer contains this text
define('ALLOWED_REFERRER', '');

// Download folder, i.e. folder where you keep all files for download.
// MUST end with slash (i.e. "/" )
define('BASE_DIR','/home/user/downloads/');

// log downloads?  true/false
define('LOG_DOWNLOADS',true);

// log file name
define('LOG_FILE','downloads.log');

// Allowed extensions list in format 'extension' => 'mime type'
// If myme type is set to empty string then script will try to detect mime type 
// itself, which would only work if you have Mimetype or Fileinfo extensions
// installed on server.
$allowed_ext = array (

  // archives
  'zip' => 'application/zip',

  // documents
  'pdf' => 'application/pdf',
  'doc' => 'application/msword',
  'xls' => 'application/vnd.ms-excel',
  'ppt' => 'application/vnd.ms-powerpoint',
  
  // executables
  'exe' => 'application/octet-stream',

  // images
  'gif' => 'image/gif',
  'png' => 'image/png',
  'jpg' => 'image/jpeg',
  'jpeg' => 'image/jpeg',

  // audio
  'mp3' => 'audio/mpeg',
  'wav' => 'audio/x-wav',

  // video
  'mpeg' => 'video/mpeg',
  'mpg' => 'video/mpeg',
  'mpe' => 'video/mpeg',
  'mov' => 'video/quicktime',
  'avi' => 'video/x-msvideo'
);



####################################################################
###  DO NOT CHANGE BELOW
####################################################################

// If hotlinking not allowed then make hackers think there are some server problems
if (ALLOWED_REFERRER !== ''
&& (!isset($_SERVER['HTTP_REFERER']) || strpos(strtoupper($_SERVER['HTTP_REFERER']),strtoupper(ALLOWED_REFERRER)) === false)
) {
  die("Internal server error. Please contact system administrator.");
}

// Make sure program execution doesn't time out
// Set maximum script execution time in seconds (0 means no limit)
set_time_limit(0);

if (!isset($_GET['f']) || empty($_GET['f'])) {
  die("Please specify file name for download.");
}

// Get real file name.
// Remove any path info to avoid hacking by adding relative path, etc.
$fname = basename($_GET['f']);

// Check if the file exists
// Check in subfolders too
function find_file ($dirname, $fname, &$file_path) {

  $dir = opendir($dirname);

  while ($file = readdir($dir)) {
    if (empty($file_path) && $file != '.' && $file != '..') {
      if (is_dir($dirname.'/'.$file)) {
        find_file($dirname.'/'.$file, $fname, $file_path);
      }
      else {
        if (file_exists($dirname.'/'.$fname)) {
          $file_path = $dirname.'/'.$fname;
          return;
        }
      }
    }
  }

} // find_file

// get full file path (including subfolders)
$file_path = '';
find_file(BASE_DIR, $fname, $file_path);

if (!is_file($file_path)) {
  die("File does not exist. Make sure you specified correct file name."); 
}

// file size in bytes
$fsize = filesize($file_path); 

// file extension
$fext = strtolower(substr(strrchr($fname,"."),1));

// check if allowed extension
if (!array_key_exists($fext, $allowed_ext)) {
  die("Not allowed file type."); 
}

// get mime type
if ($allowed_ext[$fext] == '') {
  $mtype = '';
  // mime type is not set, get from server settings
  if (function_exists('mime_content_type')) {
    $mtype = mime_content_type($file_path);
  }
  else if (function_exists('finfo_file')) {
    $finfo = finfo_open(FILEINFO_MIME); // return mime type
    $mtype = finfo_file($finfo, $file_path);
    finfo_close($finfo);  
  }
  if ($mtype == '') {
    $mtype = "application/force-download";
  }
}
else {
  // get mime type defined by admin
  $mtype = $allowed_ext[$fext];
}

// Browser will try to save file with this filename, regardless original filename.
// You can override it if needed.

if (!isset($_GET['fc']) || empty($_GET['fc'])) {
  $asfname = $fname;
}
else {
  // remove some bad chars
  $asfname = str_replace(array('"',"'",'\\','/'), '', $_GET['fc']);
  if ($asfname === '') $asfname = 'NoName';
}

// set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mtype");
header("Content-Disposition: attachment; filename=\"$asfname\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);

// download
// @readfile($file_path);
$file = @fopen($file_path,"rb");
if ($file) {
  while(!feof($file)) {
    print(fread($file, 1024*8));
    flush();
    if (connection_status()!=0) {
      @fclose($file);
      die();
    }
  }
  @fclose($file);
}

// log downloads
if (!LOG_DOWNLOADS) die();

$f = @fopen(LOG_FILE, 'a+');
if ($f) {
  @fputs($f, date("m.d.Y g:ia")."  ".$_SERVER['REMOTE_ADDR']."  ".$fname."\n");
  @fclose($f);
}

?>

I've compared with the original script and it appears both use $_GET to determine the filename. Is that how it should be? And it appears it is the variable $file_path that determines the path of the file. Perhaps you should at the end of your script add the following to check if it is correct.

die($file_path);

If that does reviel the true path then it will probably be because your server can't handle the live streaming in that last while loop. BTW, have you tried using the original script to see if it works because there is a chance of a compatibility problem. And might be easier if I just place in the mysql functionality for you if the original script does work.

The original script worked fine yeah.

Try something like the following but only edit before the ####### comments. The mysql query has been normalised as I would call it and all you need to do is correct the table name and column name in the query as well as the column name in the resultrow[] array. Hope this code is of some good use to you.

<?php
//mysql connections
$result=mysql_query('SELECT * FROM `tablename` WHERE `columnname`="'.mysql_real_escape_string($idx).'"');
if (mysql_num_rows($result)==0) {
die ('No matching downloads found in database');
}
$resultrow=mysql_fetch_array($result)
$filenamezzz=resultrow['columnname'];
unset($resultrow);

###############################################################
# File Download 1.3
###############################################################
# Visit http://www.zubrag.com/scripts/ for updates
###############################################################
# Sample call:
#    download.php?f=phptutorial.zip
#
# Sample call (browser will try to save with new file name):
#    download.php?f=phptutorial.zip&fc=php123tutorial.zip
###############################################################

// Allow direct file download (hotlinking)?
// Empty - allow hotlinking
// If set to nonempty value (Example: example.com) will only allow downloads when referrer contains this text
define('ALLOWED_REFERRER', '');

// Download folder, i.e. folder where you keep all files for download.
// MUST end with slash (i.e. "/" )
define('BASE_DIR','/home/user/downloads/');

// log downloads?  true/false
define('LOG_DOWNLOADS',true);

// log file name
define('LOG_FILE','downloads.log');

// Allowed extensions list in format 'extension' => 'mime type'
// If myme type is set to empty string then script will try to detect mime type 
// itself, which would only work if you have Mimetype or Fileinfo extensions
// installed on server.
$allowed_ext = array (

  // archives
  'zip' => 'application/zip',

  // documents
  'pdf' => 'application/pdf',
  'doc' => 'application/msword',
  'xls' => 'application/vnd.ms-excel',
  'ppt' => 'application/vnd.ms-powerpoint',
  
  // executables
  'exe' => 'application/octet-stream',

  // images
  'gif' => 'image/gif',
  'png' => 'image/png',
  'jpg' => 'image/jpeg',
  'jpeg' => 'image/jpeg',

  // audio
  'mp3' => 'audio/mpeg',
  'wav' => 'audio/x-wav',

  // video
  'mpeg' => 'video/mpeg',
  'mpg' => 'video/mpeg',
  'mpe' => 'video/mpeg',
  'mov' => 'video/quicktime',
  'avi' => 'video/x-msvideo'
);



####################################################################
###  DO NOT CHANGE BELOW
####################################################################

// If hotlinking not allowed then make hackers think there are some server problems
if (ALLOWED_REFERRER !== ''
&& (!isset($_SERVER['HTTP_REFERER']) || strpos(strtoupper($_SERVER['HTTP_REFERER']),strtoupper(ALLOWED_REFERRER)) === false)
) {
  die("Internal server error. Please contact system administrator.");
}

// Make sure program execution doesn't time out
// Set maximum script execution time in seconds (0 means no limit)
set_time_limit(0);

if (!isset($filenamezzz) || empty($filenamezzz)) {
  die("Please specify file name for download.");
}

// Get real file name.
// Remove any path info to avoid hacking by adding relative path, etc.
$fname = basename($filenamezzz);

// Check if the file exists
// Check in subfolders too
function find_file ($dirname, $fname, &$file_path) {

  $dir = opendir($dirname);

  while ($file = readdir($dir)) {
    if (empty($file_path) && $file != '.' && $file != '..') {
      if (is_dir($dirname.'/'.$file)) {
        find_file($dirname.'/'.$file, $fname, $file_path);
      }
      else {
        if (file_exists($dirname.'/'.$fname)) {
          $file_path = $dirname.'/'.$fname;
          return;
        }
      }
    }
  }

} // find_file

// get full file path (including subfolders)
$file_path = '';
find_file(BASE_DIR, $fname, $file_path);

if (!is_file($file_path)) {
  die("File does not exist. Make sure you specified correct file name."); 
}

// file size in bytes
$fsize = filesize($file_path); 

// file extension
$fext = strtolower(substr(strrchr($fname,"."),1));

// check if allowed extension
if (!array_key_exists($fext, $allowed_ext)) {
  die("Not allowed file type."); 
}

// get mime type
if ($allowed_ext[$fext] == '') {
  $mtype = '';
  // mime type is not set, get from server settings
  if (function_exists('mime_content_type')) {
    $mtype = mime_content_type($file_path);
  }
  else if (function_exists('finfo_file')) {
    $finfo = finfo_open(FILEINFO_MIME); // return mime type
    $mtype = finfo_file($finfo, $file_path);
    finfo_close($finfo);  
  }
  if ($mtype == '') {
    $mtype = "application/force-download";
  }
}
else {
  // get mime type defined by admin
  $mtype = $allowed_ext[$fext];
}

// Browser will try to save file with this filename, regardless original filename.
// You can override it if needed.

if (!isset($_GET['fc']) || empty($_GET['fc'])) {
  $asfname = $fname;
}
else {
  // remove some bad chars
  $asfname = str_replace(array('"',"'",'\\','/'), '', $_GET['fc']);
  if ($asfname === '') $asfname = 'NoName';
}

// set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mtype");
header("Content-Disposition: attachment; filename=\"$asfname\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);

// download
// @readfile($file_path);
$file = @fopen($file_path,"rb");
if ($file) {
  while(!feof($file)) {
    print(fread($file, 1024*8));
    flush();
    if (connection_status()!=0) {
      @fclose($file);
      die();
    }
  }
  @fclose($file);
}

// log downloads
if (!LOG_DOWNLOADS) die();

$f = @fopen(LOG_FILE, 'a+');
if ($f) {
  @fputs($f, date("m.d.Y g:ia")."  ".$_SERVER['REMOTE_ADDR']."  ".$fname."\n");
  @fclose($f);
}

?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.