By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,839 Members | 2,270 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,839 IT Pros & Developers. It's quick & easy.

Error in Downloading the text file

P: 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
Share this Question
Share on Google+
8 Replies


Atli
Expert 5K+
P: 5,058
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

P: 21
@Atli
Can you help me how to attach a text file with this
Mar 4 '10 #3

P: 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
Expert 5K+
P: 5,058
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

P: 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, 294 views)
Mar 5 '10 #6

Atli
Expert 5K+
P: 5,058
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

P: 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
Expert 5K+
P: 5,058
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

Post your reply

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