I have a simple download script that can be found below:
if (isset($_GET['name'])){
$name = $_GET['name'];
$stmt = $conn->prepare("SELECT link_to_policy FROM policies WHERE name = ? LIMIT 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$result2 = $result->fetch_assoc();
$policytodownload = $result2["link_to_policy"];
if (file_exists($policytodownload)) {
header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
header("Content-Type: application/msword");
header("Content-Type: application/pdf");
header('Content-Disposition: attachment');
header("Cache-Control: no-cache");
header('Content-Length: ' . filesize($policytodownload));
ob_clean();
flush();
readfile($policytodownload);
exit;
}
}
link_to_policy column contains the full path to the file where the policy has been saved. After clicking on the link, the file is downloaded, but after clicking on the file, even if it is a word document, I receive an error message in Chrome (all the PDF files are meant to be opened there): Failed to load PDF document.
Can you please help me? Thank you!
Don't send multiple Content-type
headers, send the appropriate type for the file extension.
if (isset($_GET['name'])){
$name = $_GET['name'];
$stmt = $conn->prepare("SELECT link_to_policy FROM policies WHERE name = ? LIMIT 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$result2 = $result->fetch_assoc();
$policytodownload = $result2["link_to_policy"];
if (file_exists($policytodownload)) {
$type_map = ['xls' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'doc' => 'application/msword',
'pdf' => 'application/pdf'];
$ext = pathinfo($policytodownload, PATHINFO_EXTENSION);
if (isset($type_map[$ext])) {
header("Content-Type: {$type_map[$ext]}");
}
header("Cache-Control: no-cache");
header('Content-Length: ' . filesize($policytodownload));
ob_clean();
flush();
readfile($policytodownload);
exit;
}
}