How to download existing pdf, excel & txt file in codeigniter?

Member

by orpha , in category: PHP Frameworks , a month ago

How to download existing pdf, excel & txt file in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , a month ago

@orpha 

To download existing files in CodeIgniter, you can use the following method:

  1. Create a controller in your CodeIgniter application to handle the download process. You can create a new controller or use an existing one. For this example, let's create a new controller called Download.
  2. In the Download controller, create a method to handle the file download process. You can use the following code as a starting point:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public function index()
{
    $filename = 'path_to_your_file.pdf'; // Change this to the path of the PDF, Excel, or text file you want to download

    // Check if the file exists
    if (file_exists($filename)) {
        // Set the appropriate headers
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filename));
        
        // Flush the output buffer
        ob_clean();
        flush();
        
        // Read the file and output its contents
        readfile($filename);
    } else {
        echo 'File not found';
    }
}


  1. Replace 'path_to_your_file.pdf' with the actual path to the file you want to download. You can also change the Content-Type header based on the type of file you are downloading (e.g., application/pdf for PDF files, application/vnd.ms-excel for Excel files, text/plain for text files).
  2. Use the following URL to trigger the file download process in your browser:
1
http://localhost/your_project_name/index.php/download


That's it! You should now be able to download existing PDF, Excel, or text files in CodeIgniter using the above method.