I am trying to build a website people can fill/upload necessary information in a form. Based on these information, the server does some computation, generates an output file and return the file. Everything goes well except the last step of returning. Following is a simplified version of my site that you can test directly. In this example, it should return a file containing the file name uploaded by the user while stay on the same page. However, it actually returns the html code of the page and the file name. What should I do to get only the output file not the html code? Thanks a lot!
I tried with flask, and everything went well. Now, for some reason I would like to translate everything to php. I am really new to website building and lack a lot of background knowledge.
<!DOCTYPE html>
<html>
<body>
<form action="" method="POST" autocomplete="on"
enctype="multipart/form-data">
<div> Upload your file: <input type="file" name="file"/> </div>
<input style="margin-left: 0.5em;" type="submit" id="click"
value="Click Me!" name='submit_btn'/>
</form>
<?php
if(isset($_POST['submit_btn']))
{
$fp = fopen("./output.txt", "w");
fwrite($fp, $_FILES['file']['name']."
");
fclose($fp);
header("Content-Type:text/plain");
header("Content-Type: application/download");
header('Content-Disposition: attachment;
filename="output.txt"');
readfile("output.txt");
}
?>
</html>
You're trying to return both HTML and a file. Each HTTP request can result in only one or the other. Separate your concerns. Start with a PHP resource which only returns the file you posted to it:
<?php
if(isset($_POST['submit_btn']))
{
$fp = fopen("./output.txt", "w");
fwrite($fp, $_FILES['file']['name']."
");
fclose($fp);
header("Content-Type:text/plain");
header("Content-Type: application/download");
header('Content-Disposition: attachment;
filename="output.txt"');
readfile("output.txt");
}
?>
Then write an HTML page which posts to that PHP resource:
<!DOCTYPE html>
<html>
<body>
<form action="yourPHPFileAbove.php" method="POST" autocomplete="on"
enctype="multipart/form-data">
<div> Upload your file: <input type="file" name="file"/> </div>
<input style="margin-left: 0.5em;" type="submit" id="click"
value="Click Me!" name='submit_btn'/>
</form>
</body>
</html>
Note specifically how the action
attribute in the <form>
posts to a specific PHP resource, not just back to itself.