在php下载问题..返回无效文件?

时间:2012-09-25 06:00:21

标签: php

  

可能重复:
  try to download file and getting invalid file in response in core php

$filename=gallery/downloads/poster/large/h.jpg  

下载文件的路径是正确的,但不知道为什么它会给出无效文件作为回报......

 $filename = $_GET["filename"]; 
 $buffer = file_get_contents($filename);

    /* Force download dialog... */
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header('Content-Type: image/jpeg');

    /* Don't allow caching... */
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

    /* Set data type, size and filename */
    header("Content-Type: application/octet-stream");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . strlen($buffer));
    header("Content-Disposition: attachment; filename=$filename");

    /* Send our file... */
   echo $buffer;

如果你有更好的方式,请分享....先谢谢。

1 个答案:

答案 0 :(得分:1)

更好的解决方案是:

$filename = $_GET["filename"];
// Validate the filename (You so don't want people to be able to download
// EVERYTHING from your site...)

if (!file_exists($filename))
{
    header('HTTP/1.0 404 Not Found');
    die();
}
// A check of filemtime and IMS/304 management would be good here

// Be sure to disable buffer management if needed
while(ob_get_level()) {
   ob_end_clean();
}

// Do not send out full path.
$basename = basename($filename);

Header('Content-Type: application/download');
Header("Content-Disposition: attachment; filename=\"$basename\"");
header('Content-Transfer-Encoding: binary'); // Not really needed
Header('Content-Length: ' . filesize($filename));
Header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

readfile($filename);

那说,“无效文件”是什么意思?长度不好?零长度?文件名不好?错误的MIME类型?文件内容错误?你眼前的一切都可能清楚你的意思,但从我们的目的来看,它远非显而易见。