I am attempting to create a directory tree based on a folder structure and various files in it using Codeigniter as a platform. I have the view working fine (except for links for files to downlaod the specified file.) I am very new to Jquery and java My code was based on something out on the Interwebs that mentions being able to add download links but nothing explaining how.
<html>
<?PHP if ($_SESSION['profilepath'] != NULL) { ?>
<div id="files">
<?php //print_r($folders);?>
</div>
<script type="text/javascript">
$(document).ready(function() {
var files = <?php print_r(json_encode($folders)); ?>;
var file_tree = build_file_tree(files);
file_tree.appendTo('#files');
function build_file_tree(files) {
var tree = $('<ul>');
for (x in files) {
if (typeof files[x] == "object") {
var span = $('<span>').html(x).appendTo(
$('<li>').appendTo(tree).addClass('folder')
);
var subtree = build_file_tree(files[x]).hide();
span.after(subtree);
span.click(function() {
$(this).parent().find('ul:first').toggle();
});
} else {
$('<li>').html(files[x]).appendTo(tree).addClass('file').click(function(){
window.location=$(this).find("a").attr("href");return false;})
//The click() function in the line above is where my links for download should be but I am unsure of what to do from here.
}
}
return tree;
}
});
</script>
</head>
<body>
<?PHP
} else {
$error = "Your user path is not set.";
print_r($error);
}
?>
</body>
</html>
hmm its more a php thing i think? you set the link to your php script passing the filename as a variable
href="download.php?file=folder\folder\folder\filename.ext" (might want to hash it / url encode)
$file = (isset($_GET['file']))?$_GET['file']:"";
check that its all ok etc.. then force it to show the download dialog
if (!is_readable($file)) die('File not found or inaccessible!');
$size = filesize($file);
$name = rawurldecode($filename);
$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",
"docx" => "application/msword",
"xls" => "application/vnd.ms-excel",
"xlsx" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg" => "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain"
);
$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-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");
header("Content-Length: " . $size);
$new_length = $size;
$chunksize = 1 * (1024 * 1024); //you may want to change this
$bytes_send = 0;
/* 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.');
Related
Hi I'm using this code to download file from folders on my server.
the problem is when I try to download files which are over 100MB the download speed is something around 20kb or 30kb how can I get more speed??
<?php
// 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','/winter/');
// 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'
);
// 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.");
}
// Nullbyte hack fix
if (strpos($_GET['f'], "\0") !== FALSE) die('');
// 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 am using following code to download a file kept on server ....now my issue is that i am not able to download file when some thing address like "http:127.0.0.0/upload/abc.pdf" file ....but i am able to download file using upload/abc.pdf i want to download my file from different folder kept on different server with different address with php on different server how can i do it .....help is must needed ...thanks in advance....
<?php
function output_file($file, $name, $mime_type='')
{
//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(
"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="'.basename($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('Error - can not open file.');
//die
die();
}
//Set the time out
set_time_limit(0);
//path to the file
/*$c=$_REQUEST['filename'];
$path=basename($c);
echo $path;
$file_path='uploads/'.$path;
*/
$file_path=$_REQUEST['filename'];
//Call the download function with file path,file name and file type
output_file($file_path, ''.$_REQUEST['filename'].'', 'text/plain');
?>
enter code here
1) When i click on DOWNLOAD button only file get downloaded...
2) And when i add " onClick="return sendMail('. $id .')"" in tag and "return false " in script only mail is sent
how can get both the facility on a single click ?
// DOWNLOAD LINK
echo 'Download';
//SCRIPT for sending mail
<script>
function sendMail(str)
{alert(str);
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","sendMail.php?q="+str,true);
xmlhttp.send();
//return false;
}
</script>
// sendMail.php
<?php include_once("includes/connection.php");
$q = ($_REQUEST['q']);
$sqlid="SELECT * FROM files_table WHERE id = '".$q."'";
$result = mysqli_query($conn,$sqlid);
$row=mysqli_fetch_array($result);
//collect data from table
$id=$row['id'];
$email =$row['user_email'];
$message=$row['message'];
$file_type=$row['file_type'];
$download=$row['file_name'];
$time=$row['time'];
$to=$email;
$from = "support#print.com"; // sender
$subject = $id.' '.$message;
$message = "
'Dear Sir,
Greetings from Printing! India's leading Printing company.
Please let us know for any queries or concerns. We are here to serve you better.
Assuring you of our best services at all times and looking forward to a long and pleasant association
Regards,
Team Printing";
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail($to,$subject,$message,"From: $from\n");
echo "Mail Sent";
?>
//download.php
<?php
//Set the time out to 0
set_time_limit(0);
//Path to the download file
$Location_to_download_files = 'downloads/'.$_REQUEST['file_to_download'];
function File_Downloads($file, $name, $mime_type='')
{
//Check premission for the file
if(!is_readable($file)) die('Sorry, the file could not found or its inaccessible.');
$size = filesize($file);
$name = rawurldecode($name);
/* Find out the MIME type. You can add any other required download file format of your choice or remove if necessary */
$known_mime_types = array(
//Programs Extensions
"html" => "text/html",
"htm" => "text/html",
//Archives
"zip" => "application/zip",
//Documents
"pdf" => "application/pdf",
"doc" => "application/msword",
"docx" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"txt" => "text/plain",
//Executables
"exe" => "application/octet-stream",
//Images
"gif" => "image/gif",
"png" => "image/png",
"jpeg"=> "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain",
//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"
);
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");
/* 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 = 1*(1024*1024); //You can change this if you wish
$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);
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
}
else
//If no permissiion
die('Error - The file you attempted to download can not be openned at the moment. Please try again or contact the site admin if this problem persist.');
//die
die();
}
//Call the function to download with file path,file name and file type
File_Downloads($Location_to_download_files, $_REQUEST['file_to_download'], 'text/plain');
?>
Remove Onclick from Donwload link(href),
and call that function in to php function
function File_Downloads($file, $name, $mime_type='')
{
//Your send mail function
echo '<script> function sendMail(str) { //your content } </script>';
}
I'm having an issue with this file download script. It takes in an ID, queries the filename, finds the extension, and sets the appropriate headers based on MIME type.
The issue is I THINK the header is being set to text/html instead of application/PDF in this case. It was working previously and now not so much. I've tried a simple force download script (http://webdesign.about.com/od/php/ht/force_download.htm) and that does work. Does anyone why this is happening?
Here is the code I'm using. (NOTE: This code was inherited. Just trying to fix this issue.)
<?php
include("includes/function_lib.php");
//*******************************************************************************//
//*******************************************************************************//
// Download Code
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",
"sql" => "text/plain",
"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, 5 Jun 2019 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 = 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); // is also possible
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else die('Error - can not open file.');
die();
}
$data_action = $_REQUEST['action'];
if($data_action == 'downloadfile') {
if(isset($_REQUEST['file'])) {
$file = $_REQUEST['file'];
} else {
$Id = $_REQUEST["id"];
$sqlNewsletter = "select case_file from tbl_case where case_id=$Id and deleteflag='active' and status='active'";
$rsNewsletter = mysql_query($sqlNewsletter);
if(mysql_num_rows($rsNewsletter) > 0) {
$rowNewsletter = mysql_fetch_object($rsNewsletter);
$file = $rowNewsletter->case_file;
}
}
$filename = explode('/', $file);
$name = $filename[2];
//$name = $file;
$result = output_file($file, $file);
//}
?>
<?php
//$result = $s->output_file($file, $name);
//$s->pageLocation("index.php?pagename=database_backup&action=done&result=$result");
}
?>
I am creating pdf files on the fly and I want to download multiple files using php. Can I write header like this
<?php
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile('original.pdf');
?>
in while loop?
Short answer is no, you need something to tell the client where the content ends and a new header begins. You can either use the zip utility and package them up for download, or you could look in to maybe a mime email format (which uses dividers throughout the document) but I'm not sure that would work over the HTTP protocol without explicitly calling it an "email" package.
I would just recommend using the zip utility. Generate the PDFs you need to, then package them up and send them off.
No. HTTP doesn't support multiple files in a single download. There was some talk about adding MIME-style semantics to HTTP messages way back when, so you could embed multiple responses in a single transfer, but that didn't go anywhere.
Unless you do something like zipping the multiple files on the server and transfer that zip, there's no way to download more than one file per request.
Step1: Create one index.php file and add following code.
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/your_folder/";
$files = scandir($path);
$count=1;
foreach ($files as $filename)
{
if($filename=="." || $filename==".." || $filename=="download.php" || $filename=="index.php")
{
//this will not display specified files
}
else
{
echo "<label >".$count.". </label>";
echo "".$filename."
";
$count++;
}
}
?>
Step2: Create one download.php file and add following code.
<?php
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');
/* 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 = 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); // 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);
//path to the file
$file_path=$_SERVER['DOCUMENT_ROOT'].'/your_folder/'.$_REQUEST['filename'];
//Call the download function with file path,file name and file type
output_file($file_path, ''.$_REQUEST['filename'].'', 'text/plain');
?>
Change 'your_folder' with you folder name in both files.
No. The standard only allows for a single file to be downloaded per request. You could, if the ZIP method suggested above is not possible, have a base page with a javascript timeout that redirects the user to each of the files, one at a time. For instance:
<script type="text/javascript">
var file_list = new Array(
'http://www.mydomain.com/filename1.file',
'http://www.mydomain.com/filename2.file',
'http://www.mydomain.com/filename3.file'
);
for (var i=0; i < file_list.length - 1; i++) {
setTimeout(function () {
document.location = file_list[i];
}, i * 1000);
}
</script>
<h1>Please wait</h1>
<p>Your download will start in a moment.</p>
Not with PHP alone. But you should be able to achieve this with some Javascript.
Make the loop from Javascript, creating new frames with the PHP pages as source.
Some browsers would warn their users of multiple file downloads though, but it should work once they accept.
Hope this helps someone searching for an answer.