php resume capability or download in chunks - php

PHP $_SERVER does not return HTTP_range key and without that key how can I perform a "resume download" or download in chunks?
if (isset($_SERVER['HTTP_RANGE'])) {
echo "find";
} else{
echo "not find";
}
i can't get $_SERVER['HTTP_RANGE'] from server .......
There is no key HTTP_RANGE when i print $_SERVER
===================================================
<?php
// get the file request, throw error if nothing supplied
// hide notices
#ini_set('error_reporting', E_ALL & ~ E_NOTICE);
//- turn off compression on the server
#apache_setenv('no-gzip', 1);
#ini_set('zlib.output_compression', 'Off');
if(!isset($_REQUEST['file']) || empty($_REQUEST['file']))
{
header("HTTP/1.0 400 Bad Request");
exit;
}
// sanitize the file request, keep just the name and extension
// also, replaces the file location with a preset one ('./myfiles/' in this example)
$file_path = $_REQUEST['file'];
$path_parts = pathinfo($file_path);
$file_name = $path_parts['basename'];
$file_ext = $path_parts['extension'];
$file_path = './myfiles/' . $file_name;
// allow a file to be streamed instead of sent as an attachment
$is_attachment = isset($_REQUEST['stream']) ? false : true;
// make sure the file exists
if (is_file($file_path))
{
$file_size = filesize($file_path);
$file = #fopen($file_path,"rb");
if ($file)
{
// set the headers, prevent caching
header("Pragma: public");
header("Expires: -1");
header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0");
header("Content-Disposition: attachment; filename=\"$file_name\"");
// set appropriate headers for attachment or streamed file
if ($is_attachment) {
header("Content-Disposition: attachment; filename=\"$file_name\"");
}
else {
header('Content-Disposition: inline;');
header('Content-Transfer-Encoding: binary');
}
// set the mime type based on extension, add yours if needed.
$ctype_default = "application/octet-stream";
$content_types = array(
"exe" => "application/octet-stream",
"zip" => "application/zip",
"mp3" => "audio/mpeg",
"mpg" => "video/mpeg",
"avi" => "video/x-msvideo",
);
$ctype = isset($content_types[$file_ext]) ? $content_types[$file_ext] : $ctype_default;
header("Content-Type: " . $ctype);
//check if http_range is sent by browser (or download manager)
if(isset($_SERVER['HTTP_RANGE']))
{
list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if ($size_unit == 'bytes')
{
//multiple ranges could be specified at the same time, but for simplicity only serve the first range
//http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
list($range, $extra_ranges) = explode(',', $range_orig, 2);
}
else
{
$range = '';
header('HTTP/1.1 416 Requested Range Not Satisfiable');
exit;
}
}
else
{
$range = '';
}
//figure out download piece from range (if set)
list($seek_start, $seek_end) = explode('-', $range, 2);
//set start and end based on range (if set), else set defaults
//also check for invalid ranges.
$seek_end = (empty($seek_end)) ? ($file_size - 1) : min(abs(intval($seek_end)),($file_size - 1));
$seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0);
//Only send partial content header if downloading a piece of the file (IE workaround)
if ($seek_start > 0 || $seek_end < ($file_size - 1))
{
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$file_size);
header('Content-Length: '.($seek_end - $seek_start + 1));
}
else
header("Content-Length: $file_size");
header('Accept-Ranges: bytes');
set_time_limit(0);
fseek($file, $seek_start);
while(!feof($file))
{
print(#fread($file, 1024*8));
ob_flush();
flush();
if (connection_status()!=0)
{
#fclose($file);
exit;
}
}
// file save was a success
#fclose($file);
exit;
}
else
{
// file couldn't be opened
header("HTTP/1.0 500 Internal Server Error");
exit;
}
}
else
{
// file does not exist
header("HTTP/1.0 404 Not Found");
exit;
}
?>

Related

File getting corrupted on downloading

I have got this code from one of the site for file downloads.
Did implemented this code but it only gets download but when I tried to view the file it shows me error in the file.
I did downloaded various file formats like pdf, docx ,doc but it always showed the error.
I have stored my uploads or say file in database. Its not in a directory.
Please suggest me some ideas over this.
The ERROR IS -
Warning: fopen(files/JAVAPROGRAMS.doc) [function.fopen]: failed to open stream: No
such file or directory in
C:\wamp\www\pages\candidate\download.php on line 75 Error - can not open file.
mysql_connect('localhost','root','') or die(mysql_error());
//echo "connected";
mysql_select_db('talent') or die(mysql_error());
function output_file($file, $name, $mime_type='')
{
$size = filesize($file);
$name = rawurldecode($name);
$known_mime_types=array(
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"jpg" => "image/jpg",
"php" => "text/plain",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"pdf" => "application/pdf",
"txt" => "text/plain",
"html"=> "text/html",
"png" => "image/png",
"jpeg"=> "image/jpg"
);
if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
}
else
{
$mime_type="application/force-download";
};
};
//turn off output buffering to decrease cpu usage
#ob_end_clean();
// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
// multipart-download and download resuming support
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end)
{
$range_end=$size-1;
}
else
{
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
}
else
{
$new_length=$size;
header("Content-Length: ".$size);
}
/* Will output the file itself */
$chunksize = 1*(1024*1024); //you may want to change this
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);
while(!feof($file) && (!connection_aborted()) && ($bytes_send<$new_length))
{
$buffer = fread($file, $chunksize);
echo($buffer);
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else
//If no permissiion
die(mysql_error());
//die
die();
}
//Set the time out
set_time_limit(0);
//path to the file
$file_path='files/'.$_REQUEST['filename'];
//Call the download function with file path,file name and file type
output_file($file_path, ''.$_REQUEST['filename'].'', 'text/plain');
Try this one. Just mention the proper file path. Hope it works for you.
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$path = "/YOUR_FILE_PATH/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\].]|[\.]{2,})", '',$_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
Try this
output_file($file_path, ''.$_REQUEST['filename'].'', '');

php resuming capacity for idm

My code is this in php file for downloading any file but resume capability showing unknown plz can u suggest me the code for that functionality
its my php page to download a file, have to change code or what to do for changing resume capability in idm ?
if(!isset($_SESSION['user_id'])){
header('location:../index.php');}
$uname=$_SESSION['uname'];
$uid= $_SESSION['user_id'];
function output_file($file, $name, $mime_type='')
{
/*
This function takes a path to a file to output ($file), the filename that the browser will see ($name) and the MIME type of the file ($mime_type, optional).
*/
//Check the file premission
//if(!is_readable($file)) die('File not found or inaccessible!');
$size = filesize($file);
$name = rawurldecode($name);
/* Figure out the MIME type | Check in array */
$known_mime_types=array(
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg"=> "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain"
);
if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
} else {
$mime_type="application/force-download";
};
};
//turn off output buffering to decrease cpu usage
#ob_end_clean();
// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
header('Content-Length: 2052595');
header('Content-Range: bytes 339843-2392437/2392438');
/* The three lines below basically make the
download non-cacheable */
header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// multipart-download and download resuming support
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}
/* Will output the file itself */
$chunksize = 3*(1024*1024); //you may want to change this
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);
while(!feof($file) &&
(!connection_aborted()) &&
($bytes_send<$new_length)
)
{
$buffer = fread($file, $chunksize);
print($buffer); //echo($buffer); // can also possible
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else
//If no permissiion
die('Error - can not open file.');
//die
die();
}
//Set the time out
set_time_limit(0);
$temp = explode("\\", $_REQUEST['filename']);
//path to the file
$file_path=$_REQUEST['filename'];
//Call the download function with file path,file name and file type
output_file($file_path, ''.$temp[3].'', 'text/plain');
?>
<?php
$uname=$_COOKIE["uname"];
//echo $uname;
$file=$_REQUEST['filename'];
$file_name="E:\\upload\\$uname\\$file";
$fid=$_REQUEST['fid'];
$con=mysql_connect("localhost","root","Net#123");
$db=mysql_select_db("file_storage",$con);
$query1=mysql_query("SELECT * FROM upload WHERE file_id=$fid");
$row1=mysql_fetch_array($query1);
if($row1)
{
$file_db=$row1['name'];
// If the requested file is exist
if(file_exists($file_name)){
// Get the file size
$file_size=filesize($file_name);
// Open the file
$fh=fopen($file_name, "r");
// Download speed in KB/s
$speed=1024;
//Initialize the range of bytes to be transferred
$start=0;
$end=$file_size-1;
//Check HTTP_RANGE variable
if(isset($_SERVER['HTTP_RANGE']) &&
preg_match('/^bytes=(\d+)-(\d*)/', $_SERVER['HTTP_RANGE'], $arr)){
// Starting byte
$start=$arr[1];
if($arr[2]){
// Ending byte
$end=$arr[2];
}
}
//Check if starting and ending byte is valid
if($start>$end || $start>=$file_size){
header("HTTP/1.1 416 Requested Range Not Satisfiable");
header("Content-Length: 0");
}
else{
// For the first time download
if($start==0 && $end==$file_size){
// Send HTTP OK header
header("HTTP/1.1 200 OK");
}
else{
// For resume download
// Send Partial Content header
header("HTTP/1.1 206 Partial Content");
// Send Content-Range header
header("Content-Range: bytes ".$start."-".$end."/".$file_size);
}
// Bytes left
$left=$end-$start+1;
// Send the other headers
header("Content-Type: application/octet-stream");
header("Accept-Ranges: bytes");
// Content length should be the bytes left
header("Content-Length: ".$left);
header("Content-Disposition: attachment; filename=".$file_db);
// Read file from the given starting bytes
fseek($fh, $start);
// Loop while there are bytes left
while($left>0){
// Bytes to be transferred
// according to the defined speed
$bytes=$speed*1024;
// Read file per size
echo fread($fh, $bytes);
// Flush the content to client
flush();
// Substract bytes left with the tranferred bytes
$left-=$bytes;
// Delay for 1 second
sleep(1);
}
}
fclose($fh);
}
else{
//If the requested file is not exist
//Display error message
echo "File not found!";
}
}
exit();
?>
This code worked for , files are downloading with resume capability...
Please see the RFC on headers on how to report your capabilities to your clients:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
14.5 Accept-Ranges
The Accept-Ranges response-header field allows the server to
indicate its acceptance of range requests for a resource:
Accept-Ranges = "Accept-Ranges" ":" acceptable-ranges
acceptable-ranges = 1#range-unit | "none"
Origin servers that accept byte-range requests MAY send
Accept-Ranges: bytes
but are not required to do so. Clients MAY generate byte-range
requests without having received this header for the resource
involved. Range units are defined in section 3.12.
Servers that do not accept any kind of range request for a
resource MAY send
Accept-Ranges: none
to advise the client not to attempt a range request.

Download php script image

Helo I'm trying to create download script in PHP... Upload form is ok and it stores file in folder 'upload/' but and file name is stored in DB, but when I download, it downloads file e.g. some image, when I want to see image it's only red X like here: image....any ideas?
<?php
include 'connect.php';
$query = "SELECT * FROM topics WHERE topic_id = '". $_GET['topic_id'] ."' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$name = $row['topic_subject'];
$file = $row['topic_file'];
header('Pragma: public');
header('Content-Description: File Transfer');
header("Content-Disposition: attachment; filename='".$file . "'");
header("Content-Type: ".mime_content_type($file)."");
header("Content-Length: " . filesize($file) ." ");
header('Content-Transfer-Encoding: binary');
readfile('uploads/',$file);
ob_clean();
flush();
?>
Looks like the issue could be in your call to readfile. You need to use a . to concatenate the file path to the file name, so replace;
readfile('uploads/',$file);
with
readfile('uploads/'.$file);
I’m using my own script for file download. Its best i find ever. You can also modify it as user requirement.
function download_file($Source_File, $Download_Name, $file_extension = '') {
/*
$Source_File = path to a file to output
$Download_Name = filename that the browser will see
$file_extension = MIME type of the file (Optional)
*/
if (!is_readable($Source_File))
die('File not found or inaccessible!');
$size = filesize($Source_File);
$Download_Name = rawurldecode($Download_Name);
/* Figure out the MIME type (if not specified) */
$known_mime_types = array(
"pdf" => "application/pdf",
"csv" => "application/csv",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg" => "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain"
);
if ($file_extension == '') {
// $file_extension = strtolower(substr(strrchr($Source_File,"."),1));
if (array_key_exists($file_extension, $known_mime_types)) {
$mime_type = $known_mime_types[$file_extension];
} else {
$mime_type = "application/force-download";
};
};
#ob_end_clean(); //off output buffering to decrease Server usage
// if IE, otherwise Content-Disposition ignored
if (ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="' . $Download_Name . '"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
header("Cache-control: private");
header('Pragma: private');
header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 3600));
// multipart-download and download resuming support
if (isset($_SERVER['HTTP_RANGE'])) {
list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
list($range) = explode(",", $range, 2);
list($range, $range_end) = explode("-", $range);
$range = intval($range);
if (!$range_end) {
$range_end = $size - 1;
} else {
$range_end = intval($range_end);
}
$new_length = $range_end - $range + 1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length = $size;
header("Content-Length: " . $size);
}
/* output the file itself */
$chunksize = 1 * (1024 * 1024); //you may want to change this
$bytes_send = 0;
if ($Source_File = fopen($Source_File, 'r')) {
if (isset($_SERVER['HTTP_RANGE']))
fseek($Source_File, $range);
while (!feof($Source_File) &&
(!connection_aborted()) &&
($bytes_send < $new_length)
) {
$buffer = fread($Source_File, $chunksize);
print($buffer); //echo($buffer); // is also possible
flush();
$bytes_send += strlen($buffer);
}
fclose($Source_File);
} else
die('Error - can not open file.');
die(1); // A response code other than 0 is a failure
}
I hope this will help you.
Cheers!
Mudassar Ali
You have to give the full path of an image to the readfile() function.

Force download a file from browser using php

I have generated csv file on link click. But I am unable to download file from browser.
Here is my code.
$filename="Payment_Received.csv";
header( 'Content-Description: File Transfer' );
header( 'Content-Disposition: attachment; filename=' . $filename );
header('Content-Type: text/csv; charset=UTF-8');
print_r($output);
// output is string comma separated if i remove die and then execute
// then csv append html data also, so I keep die
ob_flush();
die();
CSV is downloading but for it is with no content.
Please help me out.
If your script outputs this: "1","asd","asds" \n "2","sqda","asds", I believe you will have a hard time generating .csv from that my friend. For CSV output, make sure your data is quoted and escaped properly, I'm sorry to send you to php.net but this comment is the only example I could land that mentions clearly at this issue. There are some code examples on that page for csv output.
Good-luck
Function to force download a file from browser.
function output_file($file, $name, $mime_type='')
{
/*
This function takes a path to a file to output ($file),
the filename that the browser will see ($name) and
the MIME type of the file ($mime_type, optional).
If you want to do something on download abort/finish,
register_shutdown_function('function_name');
*/
if(!is_readable($file)) die('File not found or inaccessible!');
$size = filesize($file);
$name = rawurldecode($name);
/* Figure out the MIME type (if not specified) */
$known_mime_types=array(
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg"=> "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain"
);
if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
} else {
$mime_type="application/force-download";
};
};
#ob_end_clean(); //turn off output buffering to decrease cpu usage
// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
/* The three lines below basically make the
download non-cacheable */
header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// multipart-download and download resuming support
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}
/* output the file itself */
$chunksize = 1*(1024*1024); //you may want to change this
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);
while(!feof($file) &&
(!connection_aborted()) &&
($bytes_send<$new_length)
)
{
$buffer = fread($file, $chunksize);
print($buffer); //echo($buffer); // is also possible
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else die('Error - can not open file.');
die();
}
/*********************************************
Example of use
**********************************************/
/*
Make sure script execution doesn't time out.
Set maximum execution time in seconds (0 means no limit).
*/
set_time_limit(0);
$file_path='that_one_file.txt';
output_file($file_path, 'some file.txt', 'text/plain');
Please check code at:
http://w-shadow.com/blog/2007/08/12/how-to-force-file-download-with-php/

Webkit and Excel file(PHPexcel)

I have an excel file which can be downloaded..for example NAME.xlsx well it works in firefox but in webkit(safari/chrome) it appends to the name also the extension .xhtml so then name it will be NAME.xlsx.html it should be ONLY .xlsx
Here you have my headers:
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($root.'/application/to_excel/KSW.xlsx');
$this->getResponse()->setHeader('Content-type', 'application/download', true);
$this->getResponse()->setHeader('Content-type', 'application/octet-stream', true);
$this->getResponse()->setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', true);
$this->getResponse()->setHeader('Content-disposition', 'attachment;filename='.basename($root.'/application/to_excel/KSW.xlsx').'', true);
$this->getResponse()->setHeader('Cache-Control', 'max-age=0', true);
So what I'm doing wrong?
I've not had this function fail yet -- it works with all the Office 2007/2010 files that I've tried so far in Safari (Windows) and Chrome. The get_known_mime_types() function just returns a giant array of all the mime-types that my app supports -- just Google for the MIME types you need. $file is the actual path to the file on your host, and $name is the file name that displays in the download (run/save) dialog. I've also given due credit to the place I got most of it from. Hope you have luck with it too:
function file_download($file, $name, $mime_type='') {
/* The majority of this code was taken from:
* http://w-shadow.com/blog/2007/08/12/how-to-force-file-download-with-php/
*
* So a big thanks to them.
* I have modified parts of it, though, so it's not 100% borrowed.
*/
if(!is_readable($file)) die('File not found or inaccessible!');
$size = filesize($file);
$name = rawurldecode($name);
/* Figure out the MIME type (if not specified) */
$known_mime_types = get_known_mime_types();
if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
} else {
$mime_type="application/force-download";
}
}
#ob_end_clean(); //turn off output buffering to decrease cpu usage
// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
/* The three lines below basically make the download non-cacheable */
header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// multipart-download and download resuming support
if(isset($_SERVER['HTTP_RANGE'])) {
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}
/* output the file itself */
$chunksize = 1*(1024*1024); // 1MB, can be tweaked if needed
$bytes_send = 0;
if ($file = fopen($file, 'r')) {
if(isset($_SERVER['HTTP_RANGE'])) {
fseek($file, $range);
}
while(!feof($file) && (!connection_aborted()) && ($bytes_send<$new_length)) {
$buffer = fread($file, $chunksize);
print($buffer); //echo($buffer); // is also possible
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else {
die('Error - can not open file.');
}
die();
}

Categories