0

我正在使用以下代码从服务器下载 mp3 文件。该代码在我的本地系统(Windows 操作系统)中运行良好。

但是,当我将代码移动到服务器(Linux)时,我收到了一个找不到文件的错误。我确定文件路径正确且文件可读

if ($fd = fopen ($filePath, "r")) {
    $fsize = filesize($filePath);
    $path_parts = pathinfo($filePath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {                 
        case "mp3":                 
        header("Content-type: audio/mpeg"); // add here more headers for diff. extensions
        header("Content-Disposition: attachment; filename=\"".$originalFileName."\""); // use 'attachment' to force a download
        break;
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$originalFileName."\"");
    }
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
    }
}
fclose ($fd) 
4

1 回答 1

0

这是我编写该代码的方式:

// A couple of sanity checks on the file path, return a meaningful error message for debugging
if (!file_exists($filePath)) {
  header('HTTP/1.1 404 Not Found');
  exit('The requested file was not found');
} else if (!is_readable($filePath)) {
  header('HTTP/1.1 403 Forbidden');
  exit('The requested file is not accessible');
}

// Get the content type from the extension
// Consider using finfo instead: http://php.net/manual/en/ref.fileinfo.php
$contentTypes = array(
  'mp3' => 'audio/mpeg',
  'jpg' => 'image/jpeg',
  'gif' => 'image/gif'
  // etc etc
);
$ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
$contentType = (isset($contentTypes[$ext])) ? $contentTypes[$ext] : 'application/octet-stream';

// Content-* headers
header("Content-Length: ".filesize($filePath));
header("Content-Type: {$contentType}");
// You will always want the same Content-Disposition: header, regardless of file type
// The only time you would need a different one is if you want to serve "inline" content
header("Content-Disposition: attachment; filename=\"{$originalFileName}\"");

// No-Cache headers
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

// We don't want the script to time out on large files
set_time_limit(0);

// Output the file
readfile($filePath);
exit;
于 2012-05-23T11:19:15.693 回答