如果要强制下载,可以使用类似以下的内容:
<?php // Fetch the file info. $filePath = '/path/to/file/on/disk.jpg'; if(file_exists($filePath)) { $fileName = basename($filePath); $fileSize = filesize($filePath); // Output headers. header("Cache-Control: private"); header("Content-Type: application/stream"); header("Content-Length: ".$fileSize); header("Content-Disposition: attachment; filename=".$fileName); // Output file. readfile ($filePath); exit(); } else { die('The provided file path is not valid.'); }?>如果仅使用常规链接链接到此脚本,则将下载文件。
顺便说一句,上面的代码段需要在页面的开头执行(在没有任何标题或HTML输出之前。) 还要注意如果您决定基于此创建一个函数来下载任意文件,则需要-
确保您防止目录遍历(
realpath很方便),仅在接受$ _GET或$
_POST的输入时才允许从定义的区域内进行下载,等等。



