PHP文件下载无法在Linux中运行

时间:2012-05-23 10:27:18

标签: php

我使用以下代码从服务器下载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) 

1 个答案:

答案 0 :(得分: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;