Response::download with text files

Hello,

I’ve been using a custom file method for download:

'directDownload' => function ()
{
	echo Response::download($this->root(), $this->filename());
},

This is part of a product download portal for customers. We mostly distribute zip packages and installation executables, but sometimes we need to ship license files, which are essentially encrypted text files with a .lic extension. I’ve encountered some issues with them.

For example, let’s create a fox.lic file and fill the file with text The quick brown fox jumps over the lazy dog. If I upload this file to my local development environment (XAMPP on Windows 10), the product download works as expected. But on staging (Apache on Ubuntu 18.04), the whole of the download page gets appended inside the file as follows:

The quick brown fox jumps over the lazy dog<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
...

Does anyone have a solution to this issue? One workaround is to zip the file before uploading to server, but that adds an unnecessary extra step both for me and to clients.

Can you try with return instead of echo like that:

'directDownload' => function ()
{
	return Response::download($this->root(), $this->filename());
},

Just a guess, after using echo, it may be included in the stream because the page loads.

@ahmetbora That’s what I thought as well, using echo seems strange, but the download for some reason is not triggered when using return

Hmm then we need to stop the application from running. Following will works:

'directDownload' => function ()
{
	echo Response::download($this->root(), $this->filename());
    exit;
},

Not for me; apart from that, I always get a file with the extension html.

Adding exit; seems to fix the issue, at least in my case. Thanks!

I still think the response should be returned, and that actually works fine when using the method in a route.

It depends on the implementation. But essentially yes. it’s better to use return in the file method and then either echo the result or return it again.

Our system invokes downloading from the same page where downloads are listed by using url parameters. By using echo+exit it’s possible to terminate page re-rendering and only start the file download.

But now that I think about it, it might be a smarter solution to use a route handler instead…