File Download
Ok, so you want your users to be able to download an image or mp3 file, a PDF or text file, or any kind of file. This will take a very small bit of PHP - if you have understood the PHP Demystified tip, this will be easy.
-Tom
1. First, we need a link. The href attribute of the link references a PHP file that will do our work. Here's what the link looks like:
<a href="scripts/download.php">Download Here!</a>
2. Notice that I have put download.php in a scripts folder on the server just below the folder where our current .html file is located. The entire contents of download.php are:
<?php
$downloadFile = "../mp3s/casi_tango.mp3";
header("Content-Disposition: attachment; filename=Casi-Tango-DUROCHER.mp3");
readfile($downloadFile);
?>
Explanation of PHP Code:
- You will remember that a PHP variable begins with a $ sign, so we know that $downloadFile is a variable. The variable is being used to hold the path on the server of the file we wish to download.
- The next line is a PHP function call. The function is called "header" and its purpose is to generate the HTTP headers for a new page. That new page will have our file attached to it.
- The next line is another PHP function called "readfile" and it actually attaches the file to the page.
- That's it! The new page does nothing but open the familiar Open/Save dialog, at which point the user can choose to put the file wherever he or she wants on the local machine.