【发布时间】:2012-06-07 00:46:00
【问题描述】:
我正在从事的项目的后期有一个严重的问题:
我编写了一个 PHP 函数,它使用户可以通过单击其链接将图像自动下载到硬盘上。
但这很容易,因为图像已上传到网站服务器,而且我知道它的完整服务器地址。
例如:"home/clients/websites/w_apo/public_html/wp-content/uploads/image.jpg"
但现在客户希望能够从他自己的地址http://www.something.com/image.jpg 粘贴图像 URL,并且仍然能够通过单击前端的链接自动下载该图像。
我是这个编程领域的新手,所以我真的需要你的帮助。欢迎提供任何链接、建议和资源。
谢谢!
这是我目前的下载功能:
download_file($_GET['file']);
/******************************************************************/
function download_file( $fullPath ){
// Must be fresh start
if( headers_sent() )
die('Headers Sent');
// Required for some browsers
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// File Exists?
if( file_exists($fullPath) ){
// Parse Info / Get Extension
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
// Determine Content Type
switch ($ext) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile( $fullPath );
} else
die('File Not Found');
}
【问题讨论】:
-
已发布。你能告诉我如何调整吗?谢谢
-
新的图片位置会不会来自不同的来源?还是它们会位于同一台服务器上?
-
不同的来源,其中两个,但可能更多
-
这些功能在 Ajax 中不起作用
标签: php download http-headers