How can I use PHP to download a file from server or third party URL.
Also I want the exact event when the file is completely downloaded. So want to call some custom JS on that event.
Tried with pure JavaScript
I tried below snippet, but got blocked access error.
Access to fetch at ‘https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf’ from origin ‘http://localhost/test.php’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
JS Code below
let fileurl = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
fetch(fileurl)
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = fileurl;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
alert('your file has downloaded!'); // or you know, something with better UX...
})
.catch(() => alert('oh no!'));
Tried with PHP + Ajax
In this case I noticed if I call this file with browser then it’s now able to download file.
But here I cannot get the actual download complete event.
Also when I have called the PHP url using AJAX then got encoded string like below.
%PDF-1.7
%����
1 0 obj
<</Type/Catalog/Pages 2 0 R/Lang(en-GB) /StructTreeRoot 291 0 R/Outlines 285 0 R/MarkInfo<</Marked true>>/Metadata 672 0 R/ViewerPreferences 673 0 R>>
endobj
2 0 obj
PHP Code below
$url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
$filename = basename($url);
$filetype = filetype($url);
header('Content-Disposition: attachment; filename=' . $filename);
header("Content-type: " . $filetype); // act as image with right MIME type
ob_clean();
flush();
readfile($url);
Please suggest what are the best possibility to achieve this. With no complex things. Also should work with all native browsers and devices.