2

I have hit a serious problem with a project I've been working on for a while now.

A user uploads files to a course. The upload script takes the filename, replaces spaces with an underscore, removes the file extension, adds a 4 digit number and then adds the extension back on.

However, the files are uploaded perfectly to the server (when opened directly from the "uploads" folder, they are fine). When downloaded to the user's computer, the files all become corrupted except for DOCX files and images.

PDF, Excel (xlsx) and powerpoint (pptx) give an error message when the downloaded file is opened: "The file is corrupt and cannot be opened".

The code I have to download is:

<?php
class download extends Controller {

public function resource ($filename)
{

    $filepath = realpath('./uploads/resources/courses/' . $filename);

    header('Content-type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Pragma: no-cache');

    readfile($filepath);

}

}

It is an MVC, so that's why it's in a class, $filename is retrieved from a $_GET variable of the file name.

Any help would be much appreciated!

hakre
  • 193,403
  • 52
  • 435
  • 836
cbenjafield
  • 81
  • 1
  • 1
  • 5
  • 1
    Can you diff the contents of the files untouched and after download? Do they at least have exactly the same size in bytes? When you open the downloaded file in a text editor. Are there unregular content at the start or end of the file. e.g. PHP error messages? – hek2mgl Dec 23 '12 at 15:26
  • 1
    Please first double-check that `$filepath` exists (give an error message otherwise), also that no additional output is send before the `header` or after the `readfile` call. – hakre Dec 23 '12 at 15:26
  • Ok, I have managed to get it to download pdf now, but excel and powerpoint still have corruption issues. I made sure the realpath returned true. Also, the file that I uploaded in "My Documents" has the same file size as the downloaded one. – cbenjafield Dec 23 '12 at 15:48
  • There might be a line in the php script that performs the downloading that is `echo`ing or `print`ing a text. Reference [Corrupted Downloaded Files (pdf, xls, doc, ppt) PHP](https://stackoverflow.com/questions/75934495/corrupted-downloaded-files-pdf-xls-doc-ppt-php) – Osama Hussein Apr 08 '23 at 14:27

2 Answers2

3

Looks like you need

header("Content-Length: " . filesize($filepath));
ob_clean();
flush();
readfile($file);
exit;

See: How to Automatically Start a Download in PHP?

See also: Corrupted .docx download using phpdocx

Community
  • 1
  • 1
Trevor.Screws
  • 541
  • 6
  • 18
0

Are you sure the downloaded file has no space or other special characters in its file name? Because such an issue happens when spaces or other special characters are there in the file name.

Kanishk Dudeja
  • 1,201
  • 3
  • 17
  • 33