Php 强制下载外部或内部文件

Php 强制下载外部或内部文件,php,download,Php,Download,强制下载外部或内部文件,如jpg 外部文件或内部文件的方法1示例: https://example.com/photos/photo.jpg/download?force=true https://pixabay.com/images/download/wintry-69661.jpg?attachment 另外,此方法将生成下载链接 https://www.pexels.com/photo/2755165/download/ 我知道这个方法2:但我需要上面的方法1 https://down

强制下载外部或内部文件,如jpg 外部文件或内部文件的方法1示例:

https://example.com/photos/photo.jpg/download?force=true
https://pixabay.com/images/download/wintry-69661.jpg?attachment
另外,此方法将生成下载链接

https://www.pexels.com/photo/2755165/download/
我知道这个方法2:但我需要上面的方法1

https://download.example.com/images/download.php?file=9284.jpg
我有多个代码来强制下载,就像方法2一样。但我需要方法1

https://download.example.com/images/download.php?file=9284.jpg
我正在使用此PHP强制下载方法2

<?php
if(!empty($_GET['file'])){
$fileName = basename($_GET['file']);
$filePath = '/home/download.example.com/images/'.$fileName;
if(!empty($fileName) && file_exists($filePath)){
// Define headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$fileName");
header("Content-Type: image/jpeg");
header("Content-Transfer-Encoding: binary");
// Read the file
readfile($filePath);
exit;
}else{
echo 'The file does not exist.';
}
}
?>


谢谢

只需将
内容类型
标题设置为
application/octet stream
。我知道这样的代码类型,并且知道如何使用.htaccess。但不工作。是否显示或下载文件取决于浏览器根据返回的内容类型标题。您无法控制它是否决定显示“保存文件”对话框。应用程序/八位字节流内容类型应导致浏览器下载文件,但如果浏览器设置为处理该mime,则将使用设置处理程序。它“不起作用”的事实并不能帮助任何人找出原因。您的示例显示“内容类型:图像/jpeg”,它将在浏览器中显示图像。