Download Files in PHP Code
Although I created my company Web site using PHP a while ago, I actually used only a very basic feature of the PHP that I can include header and footer on very page. Web site is not a typical software, but the DRY (Don’t Repeat Yourself) rule still applies. When a new major product release coming soon, I started to update the Web site and consider some advanced feature of the PHP.
Besides the face lifting with nice graphs/styles, I also want the users to register for product download so that I have a better know who had downloaded the product and maybe for follow up emails with updates. It turns out the PHP is pretty good at it. After researching and reading other’s samples, I was able to do just that quickly.
Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.
The new process works like this: a user visit the download page and click a program of interest. Instead of downloading the product right away, a registration page is open for the user to enter basic information like name, email, etc. Once submitted, the information is sent to the backend PHP which generates an one time download link and send it to the registered email immedidately. The user can then use the link to download the program.
One issue I got into was that the download link opens the binary as text in browsers. I realized that it was caused by MIME type which was unknown by browsers and the server side PHP should return the information. The MIME type can be included in the HTTP response header with Content-Type key. With the binary program, using the “application/octet-stream” is good enough.
With the fix, the downloading worked well but with another problem: the downloaded file was named as PHP code name, for example “downloadfile.php”, regardless which program it serves. This is of course very misleading for the users, thus must be fixed.
From another product I had worked on, I knew it can be fixed with HTTP response header. After checking the Java servlet code, I “ported” it to PHP easily and it worked nicely.
Here is a working code snippet in a PHP script that serves the download link from any email after a user’s registration.
$mime_type = "application/octet-stream"; $size = filesize($secretfile); header('Content-Type: '.$mime_type); header('Content-Length: ' . $size); header('Content-Disposition: attachment; filename=' . $secretfile); readfile($SECRET_DIR . $secretfile);