1

I am new to PHP, I want to write a text file and also download it at same time by clicking on button for that, I wrote a function in PHP which will create a text file and write some content in it and also start downloading when file is generated. Now it is writing the content what I want but issue is that it is writing HTML code also in this file.

My function to write file is as below

function GenerateReportFile($content){
  $filename="test.txt";
  $handle = fopen($filename,'w') or die("can't open files");


  fwrite($handle, $content);
  fclose($handle);

  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename='.basename($filename));
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize($filename));
  readfile($filename);
  exit;
 }

and I am calling this function at my home page index.php and its code is :-

    <html>
    <head>
        <title> Formatted Report Generator </title>
    </head>
    <body>
        <form action="" method="POST">
            <input type="Text" name="txtHeaderText" placeholder="Header text"/><br/>
            <input type="number" name="txtTotalRows" title="Total number of required Rows"/>
            <button name="btn_GenerateFields">Generate Fields</button><br/>
            <button name="btn_GenerateFile">Generate File</button>
        </form>
    </body>

</head>

</html>
<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
require_once './functions/generalFunctions.php';

$genFunc = new generalFunctions(); 

        if(isset($_POST['btn_GenerateFields'])){

            echo $genFunc->GenerateFormattedHtmlForm(4);        
        }
        // writing file
        if(isset($_POST['btn_GenerateFile'])){          
            $content = "Hi this is ravi bhushan and this is a report portal";
            $genFunc->GenerateReportFile($content);
        }

Now when I am clicking on Generate File button it is generating a file in which it is writing HTML code of index.php and after that it is writing that content which I am passing in GenerateReportFile function.

also when removing following code from GenerateReportFile($content) function then it is writing file on my local drive with proper output.

 header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename='.basename($filename));
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize($filename));
  readfile($filename);
  exit;
8
  • 2
    I cannot see that you call your function GenerateReportFile() from that index file... Instead you have copied some code. Like this it is unclear what should get written into the file besides the test text defined in the index file. Please revise your question (there is an edit button!) and post your real code. Commented Aug 25, 2015 at 7:06
  • Also a general hint: it is not a good practice to have the form and the processing code in a single file (your index.php file). Both have completely different semantics, they should be stored and addresses separately. That will save you a lot of hassle later, when your code becomes more complex. Put that generation code into a separate file called "generate_file.php" or something and address it via the action property of your form tag. Commented Aug 25, 2015 at 7:11
  • Are you sure there was no HTML output before the function was called? Else you should buffer your output (clean them before you send new headers) and flush the buffers once you're done. Commented Aug 25, 2015 at 7:11
  • @arkascha sorry wrong code was posted.. please check now. Commented Aug 25, 2015 at 7:12
  • 1
    Actually it turns out that my general hint precisely (though by accident) targets your issue here. This only became clear with your revision of the code. Separate the code into separate files, and the problem will be solved. Have fun! Commented Aug 25, 2015 at 7:17

1 Answer 1

1

The problem is you can not send headers after sending text (html, text ... ) . You have to send first the html, and then ( for example JavaScript , do a redirect to another php to send the file. That would be a way to do it ( not very good ) , but it would work.

The redirect force to download and the url stays in place.

Sign up to request clarification or add additional context in comments.

1 Comment

Cool.... It worked, can you suggest me, what will be the best way, either to write php code before HTML in same file(index.php) or do something else like re-direct the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.