PHP generate file for download then redirect

In PHP, you can use the header() function to send a "Content-Disposition" header to prompt the user to download a file. Here is an example:

<?php
$file = 'path/to/file.txt';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit();
header("Location: index.php");
?>

In the above example, the script first sends headers to prompt the user to download a file named "file.txt" located in the "path/to" directory, then use readfile() function to read the contents of the file and output it to the browser, after that the script uses exit; to end the execution of the script and prevent any further output.

If you want to redirect after the download is completed, you can use the header("Location:") function as shown in the last line of the script, but keep in mind that it's important to put the header("Location:") after the exit; statement because once the script execution is ended, no more headers can be sent.