使用 PHP 按扩展名类型强制下载文件



我正在尝试在单击URL时自动下载两个文件。我在这篇文章中找到了解决方案 如何使用 PHP 强制下载文件并使用此代码<?php header("Location: http://example.com/go.exe"); ?>

我的目标是按扩展名类型下载 2 个文件,而不是使用完整的文件名 url,因为文件名每 1-2 天更改一次,但扩展名将始终保持不变。文件扩展名是.xls和.pdf。我研究了这篇文章 - 如何强制下载不同类型的扩展文件 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);
    

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

希望这样 这会帮助你

$url="https://example.com/new.jpg";
$download_name = "new-image.jpg";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename="" . $download_name . """);
readfile($url);

最新更新