我下载了一个文件,但它提供的文件无效。
这是我的download_content.php
<?php
$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");
/* 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;
?>
下载文件链接:
<a href="download_content.php?filename=/gallery/downloads/poster/large/'.$r['file'].'"> Download</a>
$r['file']
包含要下载的文件名。
包含该文件的文件夹的完整路径为:
localhost/ja/gallery/downloads/poster/large/'.$r['file'].'
ja
是htdocs
中的根文件夹。
我不知道实际问题是什么,有人可以帮帮我吗?
答案 0 :(得分:1)
如另一个问题所述,这种方式看起来更好:
$filename = $_GET["filename"];
// Validate the filename (You so don't want people to be able to download
// EVERYTHING from your site...)
// For example let's say that you hold all your files in a "download" directory
// in your website root, with an .htaccess to deny direct download of files.
// Then:
$filename = './download' . ($basename = basename($filename));
if (!file_exists($filename))
{
header('HTTP/1.0 404 Not Found');
die();
}
// A check of filemtime and IMS/304 management would be good here
// Google 'If-Modified-Since', 'If-None-Match', 'ETag' with 'PHP'
// Be sure to disable buffer management if needed
while (ob_get_level()) {
ob_end_clean();
}
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类型?文件内容错误?你眼前的一切都可能清楚你的意思,但从我们的目的来看,它远非显而易见。
UPDATE :显然找不到该文件,这意味着PHP脚本的filename=
参数错误(指的是不存在的文件)。修改了上面的代码,允许目录包含所有文件,并从那里下载。
答案 1 :(得分:1)
<?php
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
// print your data here. note the following:
// - cells/columns are separated by tabs ("\t")
// - rows are separated by newlines ("\n")
// for example:
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
?>
答案 2 :(得分:0)
您的$ filename变量包含完整路径,如下所示
header("Content-Disposition: attachment; filename=$filename");
这样做
$newfilename = explode("/",$filename);
$newfilename = $newfilename[count($newfilename)-1];
$fsize = filesize($filename);
Then pass new variable into header
header("Content-Disposition: attachment; filename=".$newfilename);
header("Content-length: $fsize");
//newline added as below
ob_clean();
flush();
readfile($filename);