下载文件或打开,如果文件类型是PDF

时间:2013-05-23 10:09:43

标签: php pdf file-io download

我在这里有这个代码:

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();         
}

从一个页面下载文件。它适用于下载。但我想添加一个if到那个代码.. 类似的东西:

    if (file is a PDF) {
        header('Content-type: application/pdf');
    }else{
        header('Content-Disposition: attachment; filename="'.$nome.'"');
        readfile($caminho);
        exit();
}

因此,如果文件是PDF文件,则会打开文件而不是下载文件。 我该怎么做呢?我搜索但我找不到如何检查文件类型。

编辑(正确的解决方案):

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

1 个答案:

答案 0 :(得分:0)

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

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

顺便说一下,此代码中有SQL injection vulnerability。使用prepared statements