-2

可能重复:
尝试下载文件并在核心 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;

如果你有更好的方法,请分享....提前谢谢。

4

1 回答 1

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 类型错误?文件内容错误?眼下的一切,你的意思可能很清楚,但从我们的角度来看,这远非显而易见。

于 2012-09-25T06:15:59.300 回答