I want to download a file with PHP by AJAX
This is my code, maybe someone can help why this wont work?
Download File:
$owner = $_SESSION['login_email'];
if (isset($_GET['filename'])) {
if ($_GET['filelocation'] == 'undefined') {
$dir_end = 'files/';
$dir = '../data/' . $owner . '/' . $dir_end;
} else {
$dir_end = $_GET['filelocation'];
$dir = '../data/' . $owner . '/' . $dir_end;
}
if (strpos($dir_end, '../') === false) {
$db_filename = mysqli_real_escape_string($mysqli, $_GET['filename']);
$db_filelocation = mysqli_real_escape_string($mysqli, $dir_end);
$db_fileowner = mysqli_real_escape_string($mysqli, $owner);
foreach ($mysqli->query("SELECT * FROM files WHERE filelocation='" . $db_filelocation . "' AND file='" . $db_filename . "' AND fileowner='$db_fileowner'") as $row) {
$db_filemark = $row['filemark'] . '-';
}
$filename = $db_filename;
$dlfile = $dir . $db_filemark . $db_filename;
if (file_exists($dlfile)) {
header('Content-type: application/force-download');
header('Content-Transfer-Encoding: Binary');
header('Content-length: ' . filesize($dlfile));
header('Content-Disposition: attachment; filename=' . $db_filename);
readfile($dlfile);
echo 'success.';
} else {
echo 'error.';
}
} else {
echo 'error.';
}
} else {
echo 'error.';
}
?>
JavaScript File:
$(document).on('click', '.browse-hover-download', function(e) {
var filename = $(this).parent().find('p').text();
var filelocation = current_path;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'php/download.php?filename=' + filename + '&filelocation=' + filelocation);
xmlhttp.send();
e.stopPropagation();
});
I've got no idea why it wouldn't work, all my other AJAX work perfectly, maybe anyone of you can help...
Maybe it could be it doesn't work because i'm using header's and readfile in PHP and AJAX can't fetch that information.... If someone know's a better way how to do this let me know. :)