phpdownloadheaderhttp-headersdocx

Downloading docx / doc files via browser in php


Please I am new to php and I have not been able to figure out why this code is not working. I tried downloading this docx file however, it downloads the file but when I open the file, nothing shows on the file. It is empty. I believe the file is corrupted and this is due to the code. The code is below:

<?php
    if(isset($_POST['file_name']))
    {

        $file = $_POST['file_name'];
        echo $file;

        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        header('Content-Disposition: attachment; filename='.$file.'');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile('resumeFolder/'.$file);
        exit(); 
    }
?>
<form action="force_download.php" method="post" name="downloadform">
  <input name="file_name" value=" Aunt_CC_Letter.docx" type="hidden">
  <input type="submit" value="Download the MP3">
</form>

Solution

  • $file currently holds the file name only. In readfile($file), $file should be the complete path of the file present on the server, not just the name. And it should be located on that path. I think, in your case, the problem is that the file is not present on the server.