Hello Everyone,
Are looking forward to implement a feature to download a file after submit form from your website and after that it redirects them to another page or thank you page. For example, If you want to give a option to your site visitor to auto download the file after submit the form then you will need to use our code.
I have done many research to implment auto download features before redirect to thank you page but I not found any premanent solution. Then with help of my senior I have done it myself.
So The idea is, if its the sample file, it downloads the file then redirects to a thank you page. However, if its a paid-for download(s), this file only downloads the files, but does nothing (because the page they are coming from is a list of purchased download file links, so it needs to stay on that page.
Let's explain how we can implement it into your website.
In normal way you create a HTML of the form, validate it by js/jquery validation and submit it by PHP code after that redirect the visitor to thank you page.
Now let's download file before thank you page. For that you will require to create a new download.php file and add given below code into that file.
$file ='my-file.pdf';
if (file_exists($file)) {
force_download($file); // call function to download file
}else{ echo "file does not exists";}
// FUNCTION TO FORCE A DOWNLOAD
function force_download($filename)
{
$basename = basename($filename);
$filedata = file_get_contents($filename);
if ($filedata)
{
// THESE HEADERS ARE USED ON ALL BROWSERS
header("Content-Type: application-x/force-download");
header("Content-Disposition: attachment; filename=\"$basename\"");
header("Content-length: ".(string)(strlen($filedata)));
header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
// THIS HEADER MUST BE OMITTED FOR IE 6
if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE 6'))
{
header("Cache-Control: no-cache, must-revalidate");
}
// THIS IS THE LAST HEADER
header("Pragma: no-cache");
// FLUSH THE HEADERS TO THE BROWSER
flush();
// CAPTURE THE FILE IN THE OUTPUT BUFFERS - WILL BE FLUSHED AT SCRIPT END
ob_start();
echo $filedata;
}
}
Now add js redirection in bottom of the thank you page.
<script>document.location.href='download.php';</script>
Enjoy code!