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;
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 aneditbutton!) and post your real code.actionproperty of yourformtag.