Been struggling with this problem for a while. I am trying to force a file download through javascript and PHP.
If I visit the PHP page directly it works but I want the download to start when on a different page but without success.
The URL to the file depends on a value taken from a SELECT item, however this part works as expected so I am leaving it out of the question.
Javascript
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", postUrl, true); //postUrl = http://www.example.com/downloadFile.php?url=http://www.example.com/files/test.eps
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send();
PHP
$url = "http://www.example.com/files/test.eps";
$filesize= strlen(file_get_contents($url));
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($url));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . $filesize);
readfile($url);
I have been testing with both GET and POST (not sure which one would be best, feel free to correct me) but for now I am trying to get the GET to work.
Like I said, if I visit "http://www.example.com/downloadFile.php" directly the file is downloaded and if I do console.log(xmlHttp.responseText)
the file contents is written to the console, but the file is not downloaded when making the request from the other page.
Any help would be greatly appreciated.