cks
cks

Reputation: 153

how do i let user download file from a server

I am using mssql server and CI in which it auto backups the db file into certain folder now I need to let the user download the file from the server to her local machine.

$filename = basename($_GET['file']);
  // Specify file path.
  $path = 'backups/hello.txt';
  $download_file =  $path.$filename;

  if(!empty($filename)){
      // Check file is exists on given path.
      if(file_exists($download_file))
      {
        header('Content-Disposition: attachment; filename=' . $filename);  
        readfile($download_file); 
        exit;
      }
      else
      {
        echo 'File does not exists on given path';
      }
   }
}

I have tried this one but it says file is unknown.

Upvotes: 1

Views: 1683

Answers (1)

Robert
Robert

Reputation: 3483

As per php document, can you try like this

download.php

if (file_exists($file)) {
     header('Content-Description: File Transfer');
     header('Content-Type: application/octet-stream');//change your extension of your files
     header('Content-Disposition: attachment; filename="'.basename($file).'"');
     header('Expires: 0');
     header('Cache-Control: must-revalidate');
     header('Pragma: public');
     header('Content-Length: ' . filesize($file));
     readfile($file);
     exit;
  }

Upvotes: 2

Related Questions