-1

I have files uploaded on server folder and its path is saved in database. sample view of table is:

id  name    resume
1    N1   resume/abc.doc
2    N2   resume/def.pdf

On a click of a button i wish to download the files (format of file would mostly be docx, pdf) from the server to the system. The code that i have written downloads a file but it is either empty or corrupted. Can anyone please tell how to download files from server

<a href="download.php?candidateid=<? echo $candidateid ?>">Download</a>

download.php

$candidateid=$_GET['candidateid'];

$filename = "Filename.docx"; 
header("Content-Disposition: attachment; filename=\"$filename\"");
$flag = false;
$sql = "SELECT resume FROM candidates where id='".$candidateid."' ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) 
    {
        while($row = mysqli_fetch_assoc($result))
            {
                if (!$flag) 
                    {
                        // display field/column names as first row
                        echo implode("\t", array_keys($row)) . "\r\n";
                        $flag = true;
                    }
                echo implode("\t", array_values($row)) . "\r\n";
            }
    }
Sam
  • 1,381
  • 4
  • 30
  • 70
  • is the file xls or docx – Afsar Jun 21 '16 at 05:51
  • @zan it can be any file, but mostly it would be docx and pdf – Sam Jun 21 '16 at 05:54
  • @Killan i checked the link but it is not working in my case – Sam Jun 21 '16 at 06:03
  • first you set filename (to docx) then in header you set that type is excel - and last you display some random data from your database as a file content - how do you expect this to be working? get file name from the database, set proper headers and open binary file and return it's contents, or if you expose your "resume" directory to the world - just create a link and post it in href address of "a" tag... – Jerzyk Jun 21 '16 at 06:07

1 Answers1

0

Using the candidateid you can fetch the file name from your table and then store in a variable and then write the code

$file = '/path/to/your/dir/'.$file;

if(!$file){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

    // read the file from disk
    readfile($file);
} 
Sam
  • 1,381
  • 4
  • 30
  • 70