To download a file from a URL in CodeIgniter 4 (CI4), you generally have two goals: saving a remote file to your local server or forcing a browser to download a file from a remote location. CodeIgniter 4 provides native tools like the CURLRequest Class and the Response object to handle these tasks efficiently. Method 1: Saving a Remote File to Your Server
If the file is on another server, you must first read its data into a variable (using CURL or file_get_contents ) and then pass that data to the response. Example Implementation: codeigniter 4 download file from url
If the file already exists on your server, pass the path to download() . To download a file from a URL in
To allow a user to download a file directly through their browser when they click a link, you should use the download() method within the CI4 Response object. Example Implementation: If the file already exists on
public function saveRemoteFile() { $client = \Config\Services::curlrequest(); $remoteUrl = 'https://example.com'; $savePath = WRITEPATH . 'uploads/downloaded_image.jpg'; // Fetch the remote content $response = $client->get($remoteUrl); if ($response->getStatusCode() === 200) { // Save the body content to your local directory file_put_contents($savePath, $response->getBody()); return "File saved successfully to " . $savePath; } return "Failed to fetch file."; } Use code with caution. Method 2: Force Browser Download from a URL
If you need to fetch a file from a URL and save it to your server's storage, use CI4’s built-in CURLRequest service. This is more robust than standard PHP file_get_contents because it handles headers and redirects better.
public function downloadFromUrl() { $remoteUrl = 'https://example.com'; $fileName = 'my-downloaded-doc.pdf'; // Get the file data from the URL $fileData = file_get_contents($remoteUrl); if ($fileData !== false) { // Force the browser to download the data as a file return $this->response->download($fileName, $fileData); } throw new \CodeIgniter\Exceptions\PageNotFoundException("Remote file not found."); } Use code with caution. Key Considerations for File Downloads CodeIgniter 4 - Open file in browser instead of download