首页 > 解决方案 > 使用 PHP 按扩展类型强制下载文件

问题描述

我试图在单击 url 时自动下载两个文件。我在这篇文章中找到了解决方案How to force file download with PHP and using this code<?php header("Location: http://example.com/go.exe"); ?>

我的目标是按扩展名类型下载 2 个文件,而不是拥有完整的文件名 url,因为文件名将每 1-2 天更改一次,但扩展名将始终保持不变。文件扩展名为 .xls 和 .pdf。我查看了这篇文章 -如何强制下载不同类型的扩展文件 php但没有看到我正在寻找的实际代码。任何指导表示赞赏。谢谢你。

标签: php

解决方案


你需要解决两个问题:

  1. 找到正确的文件。您可以根据自己的需要以不同的方式执行此操作。请参阅此链接:从 php 中某些扩展名过滤的目录中获取文件的最佳方法

    // Returns one file from a folder with a specific extension
    // order is not guaranteed
    // locate_the_file_by_extension("/my/secret/folder/", "pdf")
    // folder/file must be readable by php
    function locate_the_file_by_extension($folder, $extension)
    {
       $files = glob($folder."*".$extension);
       if (count($files)>0)
       {
           return $files[0];
       }
       else
       { 
           throw new Exception("no files found");
       }
    
    }
    
  2. 下载文件:

    // locate_the_file_by_extension('pdf') returns the file you want to download
    $filename = locate_the_file_by_extension();
    
    $size   = filesize($filename);
    
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Transfer-Encoding: binary');
    header('Connection: Keep-Alive');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . $size);
    
    // read the file
    echo file_get_contents($filename);
    

确保没有其他内容发送到输出。额外的输出会损坏文件或标题。


推荐阅读