user1104854
user1104854

Reputation: 2167

File download is damaged from PHP, uploads fine

When I upload files to my server from the site it works fine. However, when I try to download them the file is damaged every time. If I open up the file manager on my server I can download the files through this, they work fine. I know the file is uploaded ok, it seems to be an error with the download process.

The files are saved on my server named by their ID in the table, followed by their extension. The name is retrieved from the database and that is used when downloading.

id  |  userid  |  filename   |   extension  |  size
1       2         test.jpeg       jpeg         123456

//the extension column is just for testing, yes I know it's redundant

test.jpeg would be saved on my server as 1.jpeg.

//this is the very first bit of code on the page aside from starting the session
if(isset($_POST['downloadFile'])){
    $file = new fileprocessing;
    $fileID = mysql_real_escape_string($_POST['hiddenFileDownload']);
    $file->serveFile($fileID); 
}

Here is the serveFile function which find the file and allows the user to download it

function serveFile($fileID){
    $sql = mysql_query("select * from files where id = '$fileID'");
    $file = mysql_fetch_array($sql);
    $ext = $file['extension'];

    header('Content-type: image/x-generic'); //I'm trying jpegs only right now

    header('Content-Disposition: attachment; filename="'.$file['filename'].".".$ext.'" ');

    readfile('/home/.../public_html/user_files/'. $fileID.".".$ext.' ');
}

When the file is downloaded it has the correct name. I'm not sure where this is going wrong. Am I not opening the file properly?

edit - adjusted my extension in my servefile function

Upvotes: 1

Views: 256

Answers (1)

Samuel Cook
Samuel Cook

Reputation: 16828

As weird as this sounds, I have had issues with viewing ".jpeg" file extensions in the past (i have a site where people have to upload images for products). It is possible however to rename the extension to ".jpg" and view the same file without any interuption. You might try renaming ".jpeg" extensions to ".jpg" when you upload then see if the results of downloading/viewing doesn't change.

Upvotes: 1

Related Questions