0

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";
}
4

1 回答 1

0

if (file is a PDF) {条件可以通过多种方式实现;pdf如果文件具有扩展名,则更容易认为该文件是 PDF :

if (strtolower(pathinfo($nome, PATHINFO_EXTENSION)) == 'pdf') {

顺便说一句,此代码中存在SQL 注入漏洞。使用准备好的语句

于 2013-05-23T10:22:37.887 回答