473,372 Members | 1,277 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,372 software developers and data experts.

Error in Downloading the text file

21
I used the follwing code to download the text file from my server location.

my php file to read the following code name is contacts.php
it is downloading the text file but , this text file includes the script of contacts.php too
Expand|Select|Wrap|Line Numbers
  1. $select_group = $_REQUEST[select_group];
  2. /*echo "file name ".    $select_file = $_FILES['frm_file']['name'];*/
  3.     if($select_group == 1){
  4.         $qry_contacts = "select eml_id from tbl_contacts  ";
  5.     }else{
  6.         $qry_contacts = "select eml_id from tbl_contacts where ctc_grp_name = '$select_group'";
  7.     }
  8.     $res_contacts = mysql_query($qry_contacts);
  9.     $ctr_contacts = mysql_num_rows($res_contacts);
  10.     $write_to_file ="";
  11.     for($i=0;$i<$ctr_contacts;$i++){
  12.             if($write_to_file ==""){
  13.                     $write_to_file = mysql_result($res_contacts,$i,eml_id);
  14.             }else{
  15.                     $write_to_file .= ",".mysql_result($res_contacts,$i,eml_id);
  16.             }
  17.     }     
  18. //    if($select_file ==""){
  19.         $outputfile = "/location of file/output.txt";
  20. //    }else{
  21.     //    $outputfile = $select_file;    
  22.     //}
  23.     if(!is_writable($outputfile)) {        
  24.         $file_message_flag = true;
  25.         $file_message = "Error in permissions";
  26.     }else{
  27.         $file2 = fopen($outputfile,"w");    
  28.         if(!$file2){            
  29.             $file_message_flag = true;
  30.             $file_message = "Error writing to the output file.\n";            
  31.         }else {
  32.             fwrite($file2,$write_to_file);
  33.             fclose($file2);
  34.             //$file_message_flag = true;
  35.             //$file_message = "E-mail ids Successfully Imported..";
  36.  
  37.  
  38.         }
  39.     }
  40.  
  41.  
  42.  
  43.  
  44. include("../include/global.php");
  45. $file_value = "output.txt";
  46.  
  47. define('ALLOWED_REFERRER', '');
  48.  
  49. // Download folder, i.e. folder where you keep all files for download.
  50. // MUST end with slash (i.e. "/" )
  51. define('BASE_DIR','location to the directory');
  52.  
  53. // log downloads?  true/false
  54. define('LOG_DOWNLOADS',true);
  55.  
  56. // log file name
  57. define('LOG_FILE','downloads.log');
  58.  
  59. // Allowed extensions list in format 'extension' => 'mime type'
  60. // If myme type is set to empty string then script will try to detect mime type 
  61. // itself, which would only work if you have Mimetype or Fileinfo extensions
  62. // installed on server.
  63. $allowed_ext = array (
  64.  
  65.   // archives
  66.   'zip' => 'application/zip',
  67.  
  68.   // documents
  69.   'txt' => 'application/txt',
  70.   'pdf' => 'application/pdf',
  71.   'doc' => 'application/msword',
  72.   'xls' => 'application/vnd.ms-excel',
  73.   'ppt' => 'application/vnd.ms-powerpoint',
  74.  
  75.   // executables
  76.   'exe' => 'application/octet-stream',
  77.  
  78.   // images
  79.   'gif' => 'image/gif',
  80.   'png' => 'image/png',
  81.   'jpg' => 'image/jpeg',
  82.   'jpeg' => 'image/jpeg',
  83.  
  84.   // audio
  85.   'mp3' => 'audio/mpeg',
  86.   'wav' => 'audio/x-wav',
  87.  
  88.   // video
  89.   'mpeg' => 'video/mpeg',
  90.   'mpg' => 'video/mpeg',
  91.   'mpe' => 'video/mpeg',
  92.   'mov' => 'video/quicktime',
  93.   'avi' => 'video/x-msvideo'
  94. );
  95.  
  96.  
  97.  
  98. ####################################################################
  99. ###  DO NOT CHANGE BELOW
  100. ####################################################################
  101.  
  102. // If hotlinking not allowed then make hackers think there are some server problems
  103. if (ALLOWED_REFERRER !== ''
  104. && (!isset($_SERVER['HTTP_REFERER']) || strpos(strtoupper($_SERVER['HTTP_REFERER']),strtoupper(ALLOWED_REFERRER)) === false)
  105. ) {
  106.   die("Internal server error. Please contact system administrator.");
  107. }
  108.  
  109. // Make sure program execution doesn't time out
  110. // Set maximum script execution time in seconds (0 means no limit)
  111. set_time_limit(0);
  112.  
  113. if (!isset($file_value) || empty($file_value)) {
  114.   die("Please specify file name for download.");
  115. }
  116.  
  117. // Get real file name.
  118. // Remove any path info to avoid hacking by adding relative path, etc.
  119. $fname = basename($file_value);
  120.  
  121. // Check if the file exists
  122. // Check in subfolders too
  123. function find_file ($dirname, $fname, &$file_path) {
  124.  
  125.   $dir = opendir($dirname);
  126.  
  127.   while ($file = readdir($dir)) {
  128.     if (empty($file_path) && $file != '.' && $file != '..') {
  129.       if (is_dir($dirname.'/'.$file)) {
  130.         find_file($dirname.'/'.$file, $fname, $file_path);
  131.       }
  132.       else {
  133.         if (file_exists($dirname.'/'.$fname)) {
  134.           $file_path = $dirname.'/'.$fname;
  135.           return;
  136.         }
  137.       }
  138.     }
  139.   }
  140.  
  141. } // find_file
  142.  
  143. // get full file path (including subfolders)
  144. $file_path = '';
  145. find_file(BASE_DIR, $fname, $file_path);
  146.  
  147. if (!is_file($file_path)) {
  148.   die("File does not exist. Make sure you specified correct file name."); 
  149. }
  150.  
  151. // file size in bytes
  152. $fsize = filesize($file_path); 
  153.  
  154. // file extension
  155. $fext = strtolower(substr(strrchr($fname,"."),1));
  156.  
  157. // check if allowed extension
  158. if (!array_key_exists($fext, $allowed_ext)) {
  159.   die("Not allowed file type."); 
  160. }
  161.  
  162. // get mime type
  163. if ($allowed_ext[$fext] == '') {
  164.   $mtype = '';
  165.   // mime type is not set, get from server settings
  166.   if (function_exists('mime_content_type')) {
  167.     $mtype = mime_content_type($file_path);
  168.   }
  169.   else if (function_exists('finfo_file')) {
  170.     $finfo = finfo_open(FILEINFO_MIME); // return mime type
  171.     $mtype = finfo_file($finfo, $file_path);
  172.     finfo_close($finfo);  
  173.   }
  174.   if ($mtype == '') {
  175.     $mtype = "application/force-download";
  176.   }
  177. }
  178. else {
  179.   // get mime type defined by admin
  180.   $mtype = $allowed_ext[$fext];
  181. }
  182.  
  183. // Browser will try to save file with this filename, regardless original filename.
  184. // You can override it if needed.
  185.  
  186. if (!isset($_GET['fc']) || empty($_GET['fc'])) {
  187.   $asfname = $fname;
  188. }
  189. else {
  190.   // remove some bad chars
  191.   $asfname = str_replace(array('"',"'",'\\','/'), '', $_GET['fc']);
  192.   if ($asfname === '') $asfname = 'NoName';
  193. }
  194.  
  195. // set headers
  196. header("Pragma: public");
  197. header("Expires: 0");
  198. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  199. header("Cache-Control: public");
  200. header("Content-Description: File Transfer");
  201. header("Content-Type: $mtype");
  202. //header("Content-Type: application/txt");
  203. header("Content-Disposition: attachment; filename=\"$asfname\"");
  204. //header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
  205. header("Content-Transfer-Encoding: binary");
  206. header("Content-Length: " . $fsize);
  207.  
  208.  
  209.  
  210. //header("Content-Length: " .filesize($filename));
  211. //readfile(basename($filename));
  212. // download
  213. // @readfile($file_path);
  214. $file = @fopen($file_path,"rb");
  215. if ($file) {
  216.   while(!feof($file)) {
  217.     print(fread($file, 1024*8));
  218.     flush();
  219.     if (connection_status()!=0) {
  220.       @fclose($file);
  221.       die();
  222.     }
  223.   }
  224.   @fclose($file);
  225. }
  226.  
  227. // log downloads
  228. if (!LOG_DOWNLOADS) die();
  229.  
  230. $f = @fopen(LOG_FILE, 'a+');
  231. if ($f) {
  232.   @fputs($f, date("m.d.Y g:ia")."  ".$_SERVER['REMOTE_ADDR']."  ".$fname."\n");
  233.   @fclose($f);
  234. }
  235.  
I attached the output text file with this
Mar 4 '10 #1
8 3325
Atli
5,058 Expert 4TB
Hey.

I don't see a reference to that file anywhere in this code. How exactly are they related?

I attached the output text file with this
No you didn't :)
Mar 4 '10 #2
jyaseen
21
@Atli
Can you help me how to attach a text file with this
Mar 4 '10 #3
jyaseen
21
Below is the output of my text file - output.txt

user1@exampl.com,user2@example.com
I expect only above email ids, but below script also it displays...

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html 
  3.  
  4. xmlns="http://www.w3.org/1999/xhtml">
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7. <title>Contacts</title>
  8. <link 
  9.  
  10. href="../css/css_rahma.css" type="text/css" rel="stylesheet" />
  11. <link rel="stylesheet" href="assets/style.css" type="text/css" media="all"  />
  12. <script 
  13.  
  14. language="javascript" type="text/javascript">
  15.     function ajaxFunction(){ 
  16.         var ajaxRequest;
  17.         try{
  18.             ajaxRequest = 
  19.  
  20. new XMLHttpRequest();    
  21.         }catch(e){
  22.             try{
  23.                 ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");    
  24.  
  25.  
  26.             }catch(e){
  27.                 try{
  28.                     ajaxRequest = new 
  29.  
  30. ActiveXObject("Microsoft.XMLHTTP");    
  31.                 }catch(e){.................
  32. .......................
Mar 4 '10 #4
Atli
5,058 Expert 4TB
You aren't wrapping the download script in HTML, are you?

Anything that is in the page that sends the text file is sent, not just the file itself. To put it differently; the PHP script doesn't send the text file, it is the text file. Anything that is inside it, or is included inside it, will be included in the file you receive.
Mar 4 '10 #5
jyaseen
21
@Atli
can you give a detailed replay , I don't understand what you mean by 'wrapping the download script in HTML'
Attached Files
File Type: txt output.txt (1.7 KB, 458 views)
Mar 5 '10 #6
Atli
5,058 Expert 4TB
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.     header('content-type: text/plain');
  3. ?>
  4. <html>
  5.     <head><title>This is HTML!</title></head>
  6.     <body>
  7. <?php
  8.     passthru('mytextfile.txt'); 
  9. ?>
  10.     </body>
  11. </html>
This is PHP code wrapped in HTML. This would appear as a text-file, but include the HTML. - If you wanted only to get the text from the file, you would need to get rid of the HTML
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.     header('content-type: text/plain');
  3.     passthru('mytextfile.txt'); 
  4. ?>
Mar 5 '10 #7
jyaseen
21
below is the code executing while pressing the button 'btn_export'
output of this script should be - only the selected email ids to download to text file output.txt
can you please check any mistake in this code.?
Expand|Select|Wrap|Line Numbers
  1. if(isset($_REQUEST[btn_export])){  
  2.     $select_group = $_REQUEST[select_group]; // select_group is a list box to select the choice 
  3.     if($select_group == 1){
  4.         $qry_contacts = "select eml_id from tbl_contacts  ";
  5.     }else{
  6.         $qry_contacts = "select eml_id from tbl_contacts where ctc_grp_name = '$select_group'";
  7.     }
  8.     $res_contacts = mysql_query($qry_contacts);
  9.     $ctr_contacts = mysql_num_rows($res_contacts);
  10.     $write_to_file ="";
  11.     for($i=0;$i<$ctr_contacts;$i++){
  12.             if($write_to_file ==""){
  13.                     $write_to_file = mysql_result($res_contacts,$i,eml_id);
  14.             }else{
  15.                     $write_to_file .= ",".mysql_result($res_contacts,$i,eml_id);
  16.             }
  17.     }     
  18. //    if($select_file ==""){
  19.         $outputfile = "/path to text file/output.txt";
  20. //    }else{
  21.     //    $outputfile = $select_file;    
  22.     //}
  23.     if(!is_writable($outputfile)) {        
  24.         $file_message_flag = true;
  25.         $file_message = "Permission error ";
  26.     }else{
  27.         $file2 = fopen($outputfile,"w");    
  28.         if(!$file2){            
  29.             $file_message_flag = true;
  30.             $file_message = "Error writing to the output file.\n";            
  31.         }else {
  32.             fwrite($file2,$write_to_file);
  33.             fclose($file2);
  34.             //$file_message_flag = true;
  35.             //$file_message = "E-mail ids Successfully Imported..";
  36.             $file = '/path to text file/output.txt';
  37.             header('Content-type: text/plain');
  38.             header('Content-Length: '.filesize($file));
  39.             header('Content-Disposition: attachment; filename='.$file);
  40.             //readfile($file);
  41.             passthru($file); 
  42.         }
  43.     }
  44. }
Mar 6 '10 #8
Atli
5,058 Expert 4TB
Overall, that code should not output any sort of HTML, only the text file.

There are a couple of things, though, that you may need to fix.
  • On lines #38-41 you use a $file variable. I don't see that defined anywhere. Are you sure you don't mean to use the $outputfile variable there?
  • When you specify array element names as strings, they should be quoted, just like any other string. (See lines #1 and #2 in your code)
    If they are not, PHP will generate a error notice. (Which will be printed as HTML by default.)
    Expand|Select|Wrap|Line Numbers
    1. <?php
    2. // This is WRONG!
    3. $_REQUEST[something]
    4.  
    5. // It should be like this:
    6. $_REQUEST['something']
    7. ?>

Also, you should check out SQL Injection and the mysql_real_escape_string function. - You should never pass user input directly into a SQL query without verifying that it is in fact the data you are expecting. - Failing to do so may cause problems ranging from your query failing due to invalid syntax, to you losing your entire database.
Mar 7 '10 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: puneet.bansal | last post by:
Hi, I have a frameset and in one of the frames I have two functions. This code resides in a frame named leftFrame - //This function downloads an Excel report function downloadExcelReport() {...
0
by: Rhon Stewart via DotNetMonster.com | last post by:
Hi please visit this link : http://www.eggheadcafe.com/articles/pfc/selfupdater.asp I followed all the steps for listed on the link , when I execute the application it it gives me the following...
2
by: Matt Mercer | last post by:
Hi all, Well, thanks to some smart/helpful people here my upload and download section of my website works great! I am allowing users to upload directly into the SQL database but files cannot...
0
by: Mamatha | last post by:
Hi i have one ASP page,when i click a download button in that page it downloads a file from net,and the file size is nearly 70MB,so while at the time of downloading a file the asp page...
2
by: Tomas Martinez | last post by:
Hi there! I'm trying to download a file in my asp.net web, but when downloading it from a Firefox browser, instead of downloading the example.exe file, it's downloading example.exe.htm. My code...
5
by: rony_16 | last post by:
Hi, I have a problem downloading a file . after i connect to the website and get the stream , i treing to write the file on the HD. public void SaveStreamToFile(string filePath, Stream stream) {...
6
by: cyusman | last post by:
Hi, We have just moved our application to a new webfarm server environment which utilizing hardware load balancing, SSL off-loading and HTTP compression off-loading.My application is running on...
2
by: Paulo | last post by:
Hi, after generating a text file on server and showing the path on a hyperlink component to user download the file, shows me the error below: "There is no build provider registered for the...
0
by: =?Utf-8?B?VmFuZXNzYQ==?= | last post by:
Hi all! I am having problems on installing .NET Framework 3.5 on some machines. In one machine the error is: WinVerifyTrust returned -2146762751 Wintrust not on machine Error: O arquivo...
2
Markus
by: Markus | last post by:
I want the download button to update while a file download is in progress - "Connecting", "Downloading..", etc. But with the code below, it does not update the text. I've read about...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.