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.
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:
Example of generating file for download in PHP
<?php
$file = 'path/to/file.txt';
if (!file_exists($file)) {
die('File not found.');
}
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();
?>In the above example, the script first checks if the file exists to prevent errors. It then sends headers to prompt the user to download the file, uses the readfile() function to output the contents, and calls exit() to terminate execution.
Note that server-side headers cannot reliably trigger a redirect after a forced file download begins, as the browser handles the download in a separate process. To redirect after the download is initiated, you should handle the redirect on the client side (e.g., using window.location in the page that contains the download link).