以下代码显示:
/home/my_site/www/wp-content/uploads/2017/03/2017-03-17-my_file.mp3
据我所知,这条道路是正确的。然而,当我评论echo
并下载文件时,它是一个空文件。为什么呢?
代码:
if (isset($_GET['file'])) {
clearstatcache();
$file_path = str_replace('http://www.example.com/', '', $_GET['file']);
$file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $file_path . '.mp3';
echo $file_path;
if(file_exists($file_path)) {
$file_name = basename($file_path);
$file_size = filesize($file_path);
header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$file_size);
header("Content-Disposition: attachment; filename=".$file_name);
exit();
}
else {
die('The provided file path is not valid.');
}
}
编辑:这是我在KIKO Software的建议之后所拥有的。仍然下载空文件。
<?php
if (isset($_GET['file'])) {
$file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $_GET['file'] . '.mp3';
//echo $file_path;
//$file_path = $_SERVER['SCRIPT_FILENAME'];
if (file_exists($file_path)) {
$file_name = basename($file_path);
$file_size = filesize($file_path);
header('Content-type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.$file_size);
header('Content-Disposition: attachment; filename='.$file_name);
//readfile($file_path);
exit();
}
else {
die('The provided file path is not valid.');
}
}
?>
答案 0 :(得分:3)
下载文件的简单示例:
$content = 'This is the content.';
$size = strlen($content);
$name = 'test.txt';
header('Content-type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$name);
echo $content;
确保首先使用此功能。如果它没有标题可能有问题。启用错误报告并查看:How to fix "Headers already sent" error in PHP
然后建立起来。首先下载脚本本身:
$file_path = $_SERVER['SCRIPT_FILENAME'];
if (file_exists($file_path)) {
$file_name = basename($file_path);
$file_size = filesize($file_path);
header('Content-type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.$file_size);
header('Content-Disposition: attachment; filename='.$file_name);
readfile($file_path);
exit();
}
else {
die('The provided file path is not valid.');
}
然后才尝试下载其他内容。
通过逐步解决问题,可以更容易地看出它出错的地方。