Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Download file through an AJAX call in PHP
While AJAX isn't ideal for file downloads due to browser security restrictions, you can trigger file downloads from PHP using JavaScript redirection methods like window.location or by creating downloadable links dynamically.
Using window.location for File Download
The simplest approach is to redirect the browser to a PHP script that serves the file ?
function downloadFile(fileId) {
window.location.href = '/download.php?file=' + fileId;
}
The corresponding PHP download script ?
<?php
// download.php
$fileId = $_GET['file'] ?? '';
$filePath = '/uploads/' . basename($fileId) . '.pdf';
if (file_exists($filePath)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
} else {
http_response_code(404);
echo 'File not found';
}
?>
AJAX with Dynamic Link Creation
For better user experience, create a temporary download link via AJAX ?
function downloadViaAjax(fileId) {
fetch('/generate-download-link.php', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'file=' + fileId
})
.then(response => response.json())
.then(data => {
if (data.success) {
const link = document.createElement('a');
link.href = data.downloadUrl;
link.download = data.filename;
link.click();
}
});
}
The PHP script that generates the secure download URL ?
<?php
// generate-download-link.php
header('Content-Type: application/json');
$fileId = $_POST['file'] ?? '';
$token = bin2hex(random_bytes(16));
// Store token in session or database
$_SESSION['download_tokens'][$token] = $fileId;
echo json_encode([
'success' => true,
'downloadUrl' => '/secure-download.php?token=' . $token,
'filename' => 'document.pdf'
]);
?>
Comparison
| Method | Security | User Experience | Complexity |
|---|---|---|---|
| Direct window.location | Basic | Simple redirect | Low |
| AJAX + Dynamic Link | Token-based | No page redirect | Medium |
Conclusion
Use window.location for simple file downloads or AJAX with dynamic link creation for better UX. Always validate file paths and implement proper security measures to prevent unauthorized access.
Advertisements
