Reputation: 123
I would like to make a simple HTML file generator with PHP, where user inputs some data, and the .php file generates an output with HTML code, including the data from user.
The problem is that my generator generates only a blank .html file.
The form is simple:
<form action="html_form_submit.php" method="post">
<textarea name="name" rows="2" cols="20"> </textarea>
<input type="submit" value="Submit"/></form>
And the html_form_submit.php
file:
<?php
ob_start();
$name = @$_POST['name'];
?>
<html><body>
Name: <?php echo $name; ?><br>
</body></html>
<?php
$output = ob_get_contents();
$filename = 'test.html';
!$handle = fopen($filename, 'w');
fwrite($handle, $output);
fclose($handle);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$filename").";");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
readfile($filename);
ob_end_clean();
?>
Do you know, where can the problem be?
Upvotes: 1
Views: 71
Reputation: 379
You should move invocation of ob_end_clean immediately after the $output = ob_get_contents();
.
ob_end_clean clears your buffer so the response comes back empty.
Try like this:
<?php
ob_start();
$name = @$_POST['name'];
?>
<html><body>
Name: <?php echo $name; ?><br>
</body></html>
<?php
$output = ob_get_contents();
ob_end_clean();
$filename = 'test.html';
!$handle = fopen($filename, 'w');
fwrite($handle, $output);
fclose($handle);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$filename").";");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
readfile($filename);
Upvotes: 1
Reputation: 1202
Try this
at html_form_submit.php file:
<?php
ob_start();
if(isset($_POST['name'])){
$name = $_POST['name'];
}
?>
<html><body>
Name: <?php echo $name; ?><br>
</body></html>
<?php
$output = ob_get_contents();
$filename = 'test.html';
!$handle = fopen($filename, 'w');
fwrite($handle, $output);
fclose($handle);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$filename").";");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
readfile($filename);
ob_end_clean();
?>
Upvotes: 1