I'm having trouble creating a secure download on my site. It's not uploaded yet, and it's currently being tested on the XAMPP server on my PC. It should be noted that my operating system is Windows 11. This is my code:
The user clicks on a download link (jQuery):
$(document).on('click', '.downfile', function(e) {
e.preventDefault();
var reqfile = $(this).next().val();
$.post('php/downloadfile.php', {
reqfile:reqfile
}, function(data){});
});
I divided the download file into two parts, because someone on this site said that this might be the problem. So the first part is:
<?php
$file_path = "../uploads/" . $_POST['reqfile'];
if (file_exists($file_path)) {
$_SESSION['download'] = $file_path;
header('location: startdownload.php');
}
?>
<?php
session_start();
header('Content-Description: File Transfer');
header('Content-Type: ' . mime_content_type($_SESSION['download']));
header('Content-Disposition: attachment; filename="' . basename($_SESSION['download']) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($_SESSION['download']));
ob_clean();
flush();
ob_end_flush();
readfile($_SESSION['download']);
exit;
?>
And result is:
As you can see, the file is loaded correctly, but not downloaded. And the interesting thing is that the same code was working last week and the file was being downloaded. I have only made a small change in the code that has nothing to do with this section and moved the files folder one level further, for example: It was uploads/1/test.jpg and now it is uploads/1/1/test.jpg.
How can I solve this problem?
Content-Transfer-Encodingis not an HTTP headerI divided the download file into two parts because someone on this site said that this might be the problem...no, nothing to do with that. That seems to be just creating an extra redirect, and thus the overhead of an extra HTTP request, for no useful reason. Reduce complexity and possible points of failure by just sticking to one request. And then follow other examples online (such as in the duplicate questions above, and other similar ones) which already show you how to deal with a file download using ajax functionality. This is not a new question, by a long, long way