'PHP write to file and download after POST request

I have this code which gets a custom input from the user then downloads it:

<?php
$content = "Custom Input";


$file = "file.txt";
$txt = fopen($file, "w") or die("Unable to open file!");
fwrite($txt, $content);
fclose($txt);
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
header("Content-Type: text/plain");
readfile($file);

?>

This code returns this in a text file instead of the custom input:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv

They are the first few lines of my HTML code.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source