dsiuz86842
dsiuz86842
2019-07-30 20:14
浏览 209
已采纳

PHP下载脚本错误无法加载PDF文档

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!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dora1989
    dora1989 2019-07-30 21:34
    已采纳

    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;
        }   
    }
    
    点赞 评论

相关推荐