File: /home/imensosw/demo.imensosoftware.com/matrix/admin/download_excel.php
<?php
require_once '../config.php';
// 🔥 Enable logging (NOT display in production)
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/download_error.log');
$filePath = realpath("../docs") . DIRECTORY_SEPARATOR;
$zipPath = realpath("../") . "/zip_docs/";
// Ensure zip directory exists
if (!is_dir($zipPath)) {
mkdir($zipPath, 0775, true);
}
/**
* ============================
* VALIDATE INPUT
* ============================
*/
$list = $_POST['list'] ?? '';
if (is_array($list)) {
$list = implode(',', $list); // convert array → string
}
$docNos = array_filter(array_map('intval', explode(',', $list)));
if (empty($docNos)) {
die('Invalid data');
}
/**
* ============================
* SINGLE FILE DOWNLOAD
* ============================
*/
if (count($docNos) === 1) {
$file = $docNos[0];
$file1 = $filePath . "$file/$file.xls";
$file2 = $filePath . "$file/$file.xlsx";
if (file_exists($file1)) {
$downloadFile = $file1;
} elseif (file_exists($file2)) {
$downloadFile = $file2;
} else {
die('File not found');
}
// Clean output buffer
if (ob_get_length()) ob_end_clean();
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($downloadFile) . '"');
header('Content-Length: ' . filesize($downloadFile));
header('Cache-Control: no-cache, must-revalidate');
readfile($downloadFile);
exit;
}
/**
* ============================
* MULTIPLE FILES → ZIP
* ============================
*/
$zipName = 'assignments_' . time() . '.zip';
$zipFile = $zipPath . $zipName;
$zip = new ZipArchive();
if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
die('Could not create ZIP');
}
foreach ($docNos as $file) {
$file1 = $filePath . "$file/$file.xls";
$file2 = $filePath . "$file/$file.xlsx";
if (file_exists($file1)) {
$zip->addFile($file1, "$file.xls");
} elseif (file_exists($file2)) {
$zip->addFile($file2, "$file.xlsx");
}
}
$zip->close();
if (!file_exists($zipFile)) {
die('ZIP creation failed');
}
// Clean output buffer
if (ob_get_length()) ob_end_clean();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($zipFile) . '"');
header('Content-Length: ' . filesize($zipFile));
header('Cache-Control: no-cache, must-revalidate');
readfile($zipFile);
// Cleanup (important)
unlink($zipFile);
exit;