【问题标题】:Download file or Open if file type is PDF如果文件类型为 PDF,则下载文件或打开
【发布时间】:2013-05-23 10:09:42
【问题描述】:

我这里有这段代码:

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

【问题讨论】:

标签: php pdf file-io download


【解决方案1】:

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

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

顺便说一句,这段代码中有一个SQL injection vulnerability。使用prepared statements

【讨论】:

  • 谢谢,搞定了 :) 你能告诉我我是否正确使用了准备好的语句吗?我用准备好的陈述编辑了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
相关资源
最近更新 更多