Sunny Books
What we have

PHP force download

When creating a website, we often need to provide users the functionality of file download. A force download script can give us more control over the download processing than a direct download link. For exmple, we can check user permissions, increment a counter, do something with the database, and more.

php force download a file

//-----------------------------------------------------------
// download a file
// grab the requested file's name
$file_name = $_GET['file'];

// make sure it's a file
if(is_file($file_name)) {

  // required for IE
  if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off');  }

  // get the file mime type using the file extension
  switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
    case 'pdf': $mime = 'application/pdf'; break;
    case 'zip': $mime = 'application/zip'; break;
    case 'jpeg':
    case 'jpg': $mime = 'image/jpg'; break;
    default: $mime = 'application/force-download';
  }
  header('Pragma: public');   // required
  header('Expires: 0');    // no cache
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
  header('Cache-Control: private',false);
  header('Content-Type: '.$mime);
  header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
  header('Content-Transfer-Encoding: binary');
  header('Content-Length: '.filesize($file_name));  // provide file size
  header('Connection: close');
  readfile($file_name);    // push it out
  exit();

}

php force download a CSV string

//----------------------------------------------------------------
// download a CSV string
$csv = "";
$delimiter = ",";
$arr = array(
	0 => array("id"=>101, "name"=>"Emma", "email"=>"emma@hotmail.com"),
	1 => array("id"=>102, "name"=>"Ella", "email"=>"ella@hotmail.com"),
	2 => array("id"=>103, "name"=>"Tom", "email"=>"tom@ghotmail.com"),
	3 => array("id"=>104, "name"=>"Dave", "email"=>"dave@hotmail.com"),
);
foreach ($arr as $user) {
	$rowStr = implode($delimiter, $user);
	$csv .=$rowStr."\r\n";
}
$filename = date("Y-m-d").".csv";
header("Content-type:  application/csv");
header("Content-Disposition: attachment; filename=".$filename);
echo $csv;
exit;

SUNWEB EXPERT