简体   繁体   中英

PHP file download not working in Linux

I am using the below code to download mp3 files from server. The code is working fine in my local system(Windows OS).

However, when I am moving the code to server(Linux), I am getting a file not found error. I am sure that the file paths are correct and file is readable

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) 

Here is how I would write that code:

// 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM