PHP tutorials
In this tutorial I will show you how to create a link to a file which prompts the user for a download.
To start with create two new files and call them download.php and index.php.
Open the download.php and remove the entire content which your editor added to it, then start typing the following:
First we are checking if the the url contains the parameter file and whether basename($_GET[‘file’]) and $_GET[‘file’] have the same value – this is to prevent any attackers from downloading files we don´t want them to download.
If the condition is true then we are assigning the value of the file to the variable called $filename, however if the condition is false then we are assigning NULL to the variable.
On the next line type:
This line of code creates a new variable called $err and assigns the default message which will be displayed to the user when the file is unavailable or any other problem occur.
What´s happening here is - first we check whether the $filename is NULL and if so we are displaying our message $err message. If it isn´t NULL then we are creating the variable called $path which stores the path to the file and assigns the populated name of the file to the end of it.
Next we are checking whether the file exists and is readable, if so then we are sending the appropriate http headers with file size and opening the file in binary read-only mode (rb). Then, if the file has been opened successfully, we are using the fpassthru() function to write the result to the output buffer.
If any of the condition was unsuccessfull we are displaying our $err message.
Now open index.php and type the following:
And that´s all there is to it.
Website Design Company | Website Design Company Sussex | Website Design Company Chichester | Website Design Packages | Tutorials Resources | Articles | Contact
© Web Design Tutorials – Sebastian Sulinski