0

I have a file download code using php and my code at download page is follows.

 if (file_exists($strDownload)) {

    //get the file content
     $strFile = file_get_contents($strDownload);

       //set the headers to force a download
      header("Content-type: application/force-download");
     header("Content-Disposition: attachment; filename=\"" . str_replace(" ", "_", $arrCheck['file_name']) . "\"");

      //echo the file to the user
     echo $strFile;

     //update the DB to say this file has been downloaded
       mysql_query("xxxxxxxx");

           exit;
     }

Where the function file_exists() passed with valid check and my $strDownload variable will be something like /home/public_html/uploads/myfile.zip which is located in server folder. But when I trying to download the file instead of downloading, the page displays the full encrypted source of the file. How can I make it downloadable?

EDIT: for the information, myself trying to use this bit of code inside the wordpress system and my file path will be something like http://example.com/wp-content/uploads/2016/02/myfile.zip. Also in the above mentioned code myself checking the file_exists() condition for the server path which is already mentioned above and it returns 1 as desired.

Community
  • 1
  • 1
mpsbhat
  • 2,733
  • 12
  • 49
  • 105

2 Answers2

0

Try this

        if (file_exists($file)) 
        {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit;
        }
paranoid
  • 6,799
  • 19
  • 49
  • 86
  • 1
    Same result as mentioned in question. Displaying the source code of the file instead of downloading. – mpsbhat Feb 02 '16 at 09:27
0

It is solved by using the above bit of codes at beginning of php page. Ie, before declaring the famous wordpress tag get_header();

If we use the above code after get_header(); tag of wordpress, it results in the opening of page first and hence it writes the source of the file in the page instead of downloading since the meta tags are already set.

mpsbhat
  • 2,733
  • 12
  • 49
  • 105