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");
}
?>
Related
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.
<?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.'');
?>
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 required break-line I get my output in the browser, but it does not on the text file while I am downloading the txt file.
Main thing is that I need something this kind of output
4,
Firstname lastname,address,
orderid,product name ,
eof
4,
Firstname lastname,address,
orderid,product name ,
eof
Above output I get it in the browser but when I download this txt file with the header() that output will come like below
4,Firstname lastname,address,orderid,product name ,eof,4,Firstname lastname,address,orderid,product name ,eof,
One more strange thing is that when I connect the fttp of the site and from there when I download that txt file it will show me the proper format as I need but when I use header() it will mess my txt file format
can anyone tell me the reason my code is below
<?php
include('wp-load.php');
generate_csv();
function generate_csv()
{
global $wpdb;
$Query = "SELECT posts.ID
FROM {$wpdb->posts} AS posts
LEFT JOIN {$wpdb->term_relationships} AS rel ON posts.ID=rel.object_ID
LEFT JOIN {$wpdb->term_taxonomy} AS tax USING( term_taxonomy_id )
LEFT JOIN {$wpdb->terms} AS term USING( term_id )
WHERE posts.post_type = 'shop_order'
AND posts.post_status = 'publish'
AND tax.taxonomy = 'shop_order_status'
AND term.slug NOT IN ('completed')";
//$Query = "SELECT order_id FROM wp_woocommerce_order_items";
$ResultQuery = mysql_query( $Query );
$Orders = array();
while($ResultArray = mysql_fetch_assoc($ResultQuery))
{
$Orders[] = $ResultArray['ID'];
}
/*$list = array (
array('4')
);*/
foreach($Orders as $Order)
{
$OrderReport = new WC_Order($Order);
$Query = "SELECT user_id FROM wp_usermeta WHERE meta_key = 'first_name' AND meta_value = '".$OrderReport->shipping_first_name."'";
$QueryGetUserId = mysql_query($Query);
$GetUserId = mysql_fetch_assoc($QueryGetUserId);
$Items = $OrderReport->get_items();
foreach($Items as $Item)
{
$ProductID = $Item['product_id'];
$ProductQTY = $Item['qty']; //
}
if($ProductID=='188' or $ProductID=='205')
{
if($ProductID=='188')
{
$ProductID='118945-5';
}
if($ProductID=='205')
{
$ProductID='118946-3';
}
$GetUserId_csv='42069';
$list .= '4'.PHP_EOL .$GetUserId_csv.' '.$OrderReport->id . ',' . ',' . 'FIL' .','.PHP_EOL . '' .$OrderReport->billing_first_name .' '. $OrderReport->billing_last_name . ','. $OrderReport->shipping_address_1 .','. $OrderReport->shipping_address_2 .','. $OrderReport->shipping_city.','.$OrderReport->shipping_state.','.$OrderReport->shipping_postcode.','.$OrderReport->billing_phone.','.'A'.','. 5001 .',' .PHP_EOL . ''. $ProductID .' ,' . ', '. $ProductQTY . ',' . ',' . ','.PHP_EOL .'***EOF***'.PHP_EOL;
//$list[]=array('***EOF***');
}
$CSVFile = time().'.txt';
$fp = fopen( $CSVFile, 'w');
fwrite($fp,$list);
fclose($fp);
}
$path = site_url( '/', 'relative')."/";
$file = $path.$CSVFile;
//sleep(10);
output_file($CSVFile,$CSVFile, 'text/plain'); //this is the function which help me to download the txt file
}
?>
// function of out_file is below
function output_file($Source_File, $Download_Name, $mime_type='')
{
/*
$Source_File = path to a file to output
$Download_Name = filename that the browser will see
$mime_type = 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($mime_type==''){
$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: Thu, 26 Jul 2012 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 ($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();
}
Try \n instead of EOL for the text file.
You can try \r\n instead of \n.
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 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.');