Skip to content

How to Download Files in CodeIgniter 4

Last updated on July 6, 2023

In CodeIgniter 4, you can download a file from the server using the forceDownload() method provided by the Response class. Here’s an example of how to implement file download functionality in CodeIgniter

Create a controller method to handle the download request:

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\Response;

class FileController extends Controller
{
    public function download()
    {
        $filePath = 'path/to/file.txt'; // Replace with the actual file path

        return $this->response->download($filePath, null);
    }
}

Register a route to map the URL to the controller method. Open the app/Config/Routes.php file and add the following route:

$routes->get('download', 'FileController::download');

In the above example, we create a download() method inside the FileController class. The $filePath variable should contain the actual path to the file you want to download.

Inside the download() method, we use the $this->response->download() method to initiate the file download. The first argument is the file path, and the second argument (null in this case) represents the downloaded file’s new name. If you pass null, the file will retain its original name.

The route definition maps the URL /download to the download() method of the FileController class.

Make sure to adjust the code according to your specific file path and requirements.

When the user visits the /download URL, the browser will initiate the file download with the file’s original name.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments