Passthrough File Download Tip

At some point you’re going to need to do the following in your web app:

  1. Receive a request to download a file.
  2. Authenticate the user/validate the request using some information stored in a database.
  3. Upon successful authentication/validation, deliver the file to the requestor (but deny access to the general public).

This is a pretty standard process. It’s how developers provide software downloads, how publishers and distributors provide content downloads, etc.

When you implement this process in your code, it’s important to remember to close your database connection before you start the file passthrough to the user. If you don’t do this, your database connection will unnecessarily remain open while each download thread completes. This may use up your available database connections, causing other requests to fail. It’s also a bug you’re unlikely to run across in your local development environment.

If you’re adding this functionality within a platform like WordPress, you are often working within a small subset of code while creating this feature (within a plugin in WordPress, for example). It’s very important to remember that your code for this feature is running inside a larger codebase and to account for this sort of thing accordingly.