473,569 Members | 2,729 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Error in Downloading the text file

21 New Member
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 3353
Atli
5,058 Recognized Expert Expert
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 New Member
@Atli
Can you help me how to attach a text file with this
Mar 4 '10 #3
jyaseen
21 New Member
Below is the output of my text file - output.txt

user1@exampl.co m,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 Recognized Expert Expert
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 New Member
@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, 460 views)
Mar 5 '10 #6
Atli
5,058 Recognized Expert Expert
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 New Member
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 Recognized Expert Expert
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_esca pe_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
8703
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() { var selectObj = top.topFrame.document.getElementById('id_chain'); document.forms.chain.value =
0
4994
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 error on the log file: --- ApplicationUpdateManager.StartUpdater] : The Updater has started; the target application's name is 'SayHello'. Time...
2
1439
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 exceed 1 Meg (actually 1.2M but I tell them 1 meg) and a max of five uploads per incident (it is a security incident reporting system) I do not want...
0
978
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 displayed suddenly,page can not be displayed error but the background process(file downloading) is running.How can i manage that asp page without displaying...
2
2767
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 is the following: string localfile = MyComponent.DownloadMyExe(index); Response.ClearContent(); Response.ClearHeaders();...
5
1849
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) { // If not all data was provided return false; //if (string.IsNullOrEmpty(filePath) || stream == null) // return false; // System.IO.Stream...
6
3753
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 .NET 1.1, IIS 6, Win2003. Now we are having problem when trying to download word documents located in the file server. It often says Internet...
2
1430
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 extension '.rem'. You can register one in the <compilation><buildProviderssection in machine.config or web.config. Make sure is has a...
0
1910
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 'C:\DOCUME~1\user\CONFIG~1\Temp\VSD22.tmp\WindowsInstaller3_1\WindowsInstaller-KB893803-v2-x86.exe' foi alterado desde a sua publicação inicial.
2
1095
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 Application.DoEvents() but also heard that this isn't the best route to take? If it is OK to use Application.DoEvents(), where should I use it? button1.Text =...
0
7694
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8118
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.