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.
Related
I have a php script that allows users to download large files. The script works well except for files of over around 500mb. Everytime I try to download a file that is 664mb the download stops at about 460mb ( around 15-17 mins). There is no error. What can I do? I
suspect the script is timing out but I can't see why. I've spent days trying to get it to work and just can't make any progress. Any thoughts or suggestions would be great. I'm using a hosted server so cannot try modx_sendfile sadly. I'm using php 7.0.25
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
ob_start() or die('Cannot start output buffering');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$strDownloadFolder = "files/";
//- turn off compression on the server
//#apache_setenv('no-gzip', 1);
#ini_set('zlib.output_compression', 'Off');
//Download a file more than once
$boolAllowMultipleDownload = 2;
if(!empty($_GET['key'])){
//check the DB for the key
$sql = "SELECT * FROM downloads WHERE downloadkey = '".mysqli_real_escape_string($db,$_GET['key'])."' LIMIT 1";
$resCheck=mysqli_query($db, $sql);
$arrCheck = mysqli_fetch_array($resCheck); //Create array from first result
if(!empty($arrCheck['file'])){
//check that the download time hasnt expired
if($arrCheck['expires']>=time()){
if(!$arrCheck['downloads'] OR $boolAllowMultipleDownload){
//everything is ok -let the user download it
$strDownload = $strDownloadFolder.$arrCheck['file'];
if(file_exists($strDownload)){
$file_path = $arrCheck['file'];
$path_parts = pathinfo($file_path);
$file_name = $path_parts['basename'];
$file_ext = $path_parts['extension'];
$file_path = 'files/' . $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')
{
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;
}
}else{
echo "We couldn't find the file to download.";
}
}else{
//this file has already been downloaded and multiple downloads are not allowed
echo "This file has already been downloaded.";
}
}else{
//this download has passed its expiry date
echo "This download has expired.";
}
}else{
//the download key given didnt match anything in the DB
echo "No file was found to download.";
}
}else{
//No download key wa provided to this script
echo "No download key was provided. Please return to the previous page and try again.";
}
A much simpler piece of code that still throws up the same problem (but works with smaller files) mkaes me think it is a hosting / php.ini issue although I don't know why.
<?php
$local_file = 'my_big_file.zip';
$download_file = 'my_big_file.zip';
// set the download rate limit (=> 20,5 kb/s)
if(file_exists($local_file) && is_file($local_file))
{
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);
flush();
$file = fopen($local_file, "r");
while(!feof($file))
{
// send the current file part to the browser
print fread($file, round(1024 * 1024));
// flush the content to the browser
flush();
// sleep one second
sleep(1);
}
fclose($file);}
else {
die('Error: The file '.$local_file.' does not exist!');
}
?>
This script stops downloading after about 17 minutes.
I develop a PHP code and count how much data was downloaded by the client. My code is working fine if someone directly requests my file from a browser. But if someone installs a Mozilla extensions like ‘’downthemall’’ and then the url is requested by that extension then it requests the file URL 4 times so I get the downloaded data 4 times. How do I fix this? The same happened when the user is using jDownloader software or any software.
Here is My full download code :-
<?php
function getMimeType($fileName)
{
$c_type_default = "application/octet-stream";
$content_types = array(
"exe" => "application/octet-stream",
"zip" => "application/zip",
"mp3" => "audio/mpeg",
"mpg" => "video/mpeg",
"avi" => "video/x-msvideo",
"mp4" => "video/mp4",
);
// echo isset($content_types[pathinfo($fileName, PATHINFO_EXTENSION)]) ? $content_types[pathinfo($fileName, PATHINFO_EXTENSION)] : $c_type_default;
return isset($content_types[pathinfo($fileName, PATHINFO_EXTENSION)]) ? $content_types[pathinfo($fileName, PATHINFO_EXTENSION)] : $c_type_default;
}
function output_file($file, $name)
{
/*
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);
//turn off output buffering to decrease cpu usage
#ob_end_clean();
include('../includes/configg.php');
// Start Code For Total Downloaded Data Size by The LoggedIn User
$user="select * from $TBusers where id=".$_SESSION['log_id'];
$result_user = mysqli_query($conn, $user) ;
$row = mysqli_fetch_assoc($result_user);
$lastsotrage = $row['down'];
$curr_date= $row['curr_date'];
$today_date= date('d-m-y');
$daily_downloaded_data= $row['daily_downloaded_data'];
if($curr_date != $today_date)
{
$update_curr_date="update $TBusers set curr_date ='$today_date', daily_downloaded_data =0 where id=".$_SESSION['log_id']; // Set Curr_date by Today Date For check Daily Downloaded Data Limit
mysqli_query($conn,$update_curr_date) ;
$daily_downloaded_data=0;
}
/*else
{
if($daily_downloaded_data>=(20*1024*1024*1024)){ // Check Daily Download Data Limit 20GB Exceed or not
header('Location: http://idownload.club/members/download.php');
exit;}
}*/
// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: ' . getMimeType($name));
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);
$lastsotrage= $lastsotrage + $size;
$daily_downloaded_data+=$size;
$sql="update $TBusers set down =". $lastsotrage." where id=".$_SESSION['log_id'];
$sql2="update $TBusers set daily_downloaded_data = $daily_downloaded_data where id=".$_SESSION['log_id'];
$sql3= "update test set count=count+1 where id=1" ;
mysqli_query($conn,$sql) ;
mysqli_query($conn,$sql2) ;mysqli_query($conn,$sql3) ;
file_put_contents('data.txt', print_r($_SERVER, true), FILE_APPEND);
} 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_dir=$_GET['directory'];
$file_name = str_replace("/", "", $_GET['file']);
$file_name = str_replace("\\", "", $file_name);
$file = $file_dir . "/".$file_name;
//Call the download function with file path,file name and file type
output_file($file, ''.$file_name.'');
?>
Because of segmented/parallel download.
Mentioned extensions are requesting ranges of content (as opposed to full content when accessing from browser).
This feature allows them to download file content concurrently, most often in shorter time.
Read more about partial content and range requests.
On client side, this can be changed (DownThemAll):
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
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 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.');