I have this code right here:
if(isset($_POST['file_id'])){
$file_id = $_POST['file_id'];
$query = $mysqli->query("SELECT `IdDocumento`,`nome_ficheiro`,`caminho_ficheiro`
FROM `documento`
WHERE `IdDocumento` = $file_id");
$result = $query->fetch_object();
$caminho = $result->caminho_ficheiro;
$nome = $result->nome_ficheiro;
header('Content-Disposition: attachment; filename="'.$nome.'"');
readfile($caminho);
exit();
}
which download the file from one page. It works fine for downloads. But I want to add an if to that code.. Something like:
if (file is a PDF) {
header('Content-type: application/pdf');
}else{
header('Content-Disposition: attachment; filename="'.$nome.'"');
readfile($caminho);
exit();
}
so if the file is a PDF file it opens the file instead of downloading it. How do I do this? I searched but I couldn't find how to check the file type.
EDIT (RIGHT SOLUTION):
if(isset($_POST['file_id'])){
$query = "SELECT `IdDocumento`,`nome_ficheiro`,`caminho_ficheiro`, `tamanho_ficheiro`
FROM `documento`
WHERE `IdDocumento` = ?";
if($stmt = $mysqli->prepare($query)){
$stmt->bind_param('i', $file_id);
$file_id = $_POST['file_id'];
$stmt->execute();
$stmt->bind_result($IdDocumento, $nome_ficheiro, $caminho_ficheiro, $tamanho_ficheiro);
while ($stmt->fetch()) {
if (strtolower(pathinfo($nome_ficheiro, PATHINFO_EXTENSION)) == 'pdf') {
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="'.$nome_ficheiro.'"');
readfile($caminho_ficheiro);
}else{
header('Content-Disposition: attachment; filename="'.$nome_ficheiro.'"');
readfile($caminho_ficheiro);
}
exit();
}
$stmt->close();
}else{
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
}else{
echo"Download do ficheiro falhou";
}