How can one write data into a text file, send the appropriate header, and allow for file download in PHP?
To write data into a text file, send the appropriate header, and allow for file download in PHP, you can use the following steps: 1. Open the text file for writing and write the data into it. 2. Send the appropriate header to indicate that the content is a text file and should be downloaded. 3. Use the readfile() function to output the contents of the text file for download.
<?php
// Data to be written into the text file
$data = "Hello, world!";
// Open the text file for writing
$file = fopen('example.txt', 'w');
fwrite($file, $data);
fclose($file);
// Send the appropriate header for file download
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="example.txt"');
// Output the contents of the text file for download
readfile('example.txt');
?>