我提供了使用PHP这样的zip文件下载:
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: '.filesize($location));
readfile($location);
当文件位于S3或保管箱之类的远程服务器上(我当然拥有权利)时,该如何处理?
我不喜欢任何重定向,因为用户不应该看到原始位置。
我是否需要下载文件并将其(临时)存储在服务器上?
你可以(也可能应该!)将文件存储在本地,但你不具备对。
因此,这里有一些可能的解决方案。这些示例假定$ filename已安全生成或已通过以下方式进行了清理:
$filename = preg_replace('/[^\w.]/', '', $filename); //sanitize
1)读取文件,启用allow_url_fopen :(有关更多详细信息,请参见http://www.php.net/manual/zh/features.remote-files.php)
readfile("http://url/to/your/$filename");
2)更具有缓存性,例如:
// Serve a file from a remote server.
function serveFile($filename) {
// Folder to locally cache files. Ensure your php user has write access.
$cacheFolder = '/path/to/some/cache/folder';
// URL to the folder you'll be downloading from.
$remoteHost = 'http://remote.host/path/to/folder/';
$cachedFile = "$cacheFolder$filename";
// Cache the file if we haven't already.
if (!file_exists($cachedFile)) {
// May want to test these two calls, and log failures.
file_put_contents($cachedFile, file_get_contents("$remoteHost$filename"));
}
else {
// Set the last accessed time.
touch($cachedFile);
}
readfile($cachedFile) or die ("Well, shoot");
// Optionally, clear old files from the cache.
clearOldFiles($cacheFolder);
}
// Clear old files from cache folder, based on last mtime.
// Could also clear depending on space used, etc.
function clearOldFiles($cacheFolder) {
$maxTime = 60 * 60 * 24; // 1 day: use whatever works best.
if ($handle = opendir($cacheFolder)) {
while (false !== ($file = readdir($handle))) {
if ((time() - filemtime($path.$file)) > $maxTime) {
unlink($path.$file);
}
}
}
}
3)如果您无权启用allow_url_fopen,请使用CURL。
4)如果没有安装CURL并且无法安装,请使用wget这样的外部程序。
5)最坏的情况:打开远程服务器上端口80的套接字,然后仅发送HTTP请求文件。
6)您的Web服务器可能能够执行某种代理重定向,这意味着您实际上不需要任何代码即可完成此操作,并且您将免费获得缓存和其他优化。例如,在此处查看有关Apache的mod_proxy的文档:https : //httpd.apache.org/docs/2.2/mod/mod_proxy.html
如果可以的话,选项6是最好的。除此之外,最有可能需要前两个,但是如果您愿意,我可以为其他示例填写一些示例代码:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句