prepare($sql_insert); $action = "Downloaded"; $stmt_insert->execute([$datasource_id, $person_id, $action]); } catch (PDOException $e) { // We now log the error and set a user-facing message error_log("Error logging download: " . $e->getMessage()); // Redirect with an error message, but still try to serve the file set_message("An error occurred while logging the download.", "danger"); // We do not die here, as we still want to try and serve the file } // --- 3. Retrieve File Path and Name --- $file_path = null; $file_name = null; try { $sql_select = " SELECT dspsds_filename, dspsds_title_en FROM dsps_tbl_datasource WHERE pkdspsds_id = ? "; $stmt = $pdo->prepare($sql_select); $stmt->execute([$datasource_id]); $row = $stmt->fetch(); if ($row) { $file_name = $row['dspsds_filename']; $download_label = $row['dspsds_title_en'] ?: 'datasource_' . $datasource_id; } } catch (PDOException $e) { error_log("Error retrieving file info: " . $e->getMessage()); die("An error occurred while retrieving file information."); } if (empty($file_name)) { die("File not found in the database."); } if (preg_match('/^https?:\\/\\//i', $file_name)) { header('Location: ' . $file_name); exit; } $uploadsDir = realpath(__DIR__ . '/../uploads/datasources'); if (!$uploadsDir) { error_log('Uploads directory not found for download.'); die('File storage directory is unavailable.'); } $file_path = $uploadsDir . '/' . $file_name; // --- 4. Serve the File to the User --- // Check if the file exists on the server if (file_exists($file_path)) { // Set headers to force a download header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($download_label . '_' . $file_name) . '"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file_path)); if (ob_get_level()) { ob_clean(); } flush(); // Read the file and send it to the output buffer readfile($file_path); exit; } else { die("The file could not be found on the server at the specified path."); } ?>