Search code examples
phpforce-download

Download file didn't download the expected file


I am trying to download a file that I have uploaded in the my uploads folder. The directory is like this:

xampp
  > htdocs
     > myProject
        > normal_user
           > displayfile.php  <-- my current location
        > uploads
           > myfile.pdf

This is the part of my HTML code that display the file name:

```
```` The download code below is able to be executed BUT it didn't download the intended file. Instead, it downloads a .PHP `file name: uploads` with `file type: All Files:

`

    if (isset($_GET['forcedownload'])) {

      $filepath = "M:/xampp/htdocs/myProject/uploads/" . $row_file['f_name']; // return: myfile.pdf

      if (file_exists($filepath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: ' . $row_file['f_type']); //return: application/pdf
        header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        flush(); // Flush system output buffer
        readfile($filepath);
        exit();
      } else {
        exit();
      }
      
    }

`

I have seen numerous tutorials as well as answered Stack Overflow questions with similar situation as mine but it still happens the same. I don't know what I missed...


Solution

  • echo $filepath;
    

    to see the value of this variable.

    It should probably not content the name of the file you want to download.