Reputation: 543
I have a php page that runs a bash script then downloads the output tar. The issue is that once the file is downloaded the page just keeps loading and never redirects. I have found some issues like this but nothing that seems applicable to my case. My code is as follows:
<?php
$output=shell_exec('cd /opt/dir/ && sudo ./collect_diagnostics.sh && cd -');
$rows_output = explode("Report is in ", $output);
$rows_output2 = explode(" ", $rows_output[1]);
$path_parts = pathinfo($rows_output2[0]);
$file_name = $path_parts['basename'];
$file_path = "/opt/dir/test/".$file_name;
if (is_readable($file_path )) {
header('Content-Disposition: attachment; filename="'.$file_name.'"');
ob_clean();
readfile($file_path);
} else {
echo "404 Error";
}
header( 'Location:./aps_control.php' ) ;
?>
Just to be clear I have the bash script working and the download does occur and has a valid file. The only issues seem to be that the page never finishes loading and I am not sure if this is related but the file when unpacked in 7-zip says "There are some data after the end of the payload data : version_Placeholder.tar". Also I really want to know what I am doing wrong for personal improvement.
My main resource for learning how to download files was http://www.media-division.com/the-right-way-to-handle-file-downloads-in-php/
Upvotes: 0
Views: 465
Reputation: 21774
You shouldn't try to show a page and serve the file in the same request. Just serve the file.
If you would like the user to go to a new page with a back button, you should redirect them to that page, and that page should trigger a new page that does the download. Don't combine them.
Upvotes: 1