How to allow users to download files in PHP

So, you want to allow your users to download files from your server.
Downloading files in php is a simple process.You do not need scores of lines in your code to achieve that.3 steps and you are done.
A working example for the same can be seen here.

Steps:
1- Specify content type – this will tell the browser which type of file do you wish to send to user’s browser.
2- Specify the name of the file for user and show an open/save dialog box.
3- Read the original file from your server and render it to users browser.

Here is the php code:

//download.php
//content type
header('Content-type: text/plain');
//open/save dialog box
header('Content-Disposition: attachment; filename="sample.txt"');
//read from server and write to buffer
readfile('test.txt');

Yes, thats all. Really.
We will see in a moment how this works. First remember that there must not be any line besides these lines in the file. Also note that outputting anything to the browser,like blank spaces or any html before a call to header function as it will throw an error.

First we specified a content type using the header function.header is used to send http headers to the browser.Content type will be set depending on the file type to be downloaded. It can be text/html for a html file,text/xml for xml file or application/zip for zip files. You can see a list of content types here.In our case it is text/plain as we are going to output a text file.

Next, we provided the value “attachment” for “Content-Disposition” forces an open/save dialog box on the browser. Parameter “filename” tells that the resulting file has to be saved by this name. For more information on Content-Disposition see rfc2183. User will be prompted to save the file by name sample.txt.

Finally, the readfile function. readfile reads a file from server and writes it to the outputbuffer, which in our case is users browser.The parameter test.txt here is the name of file on server.

Opening this file in your web browser will start download.Alternatively, you can provide a download link from other file also.For this, create a html file like below:

///index.html
 
<a href="download.php">Click to download</a>

Save this with whatever name you prefer. Now open it in your browser and Click the link. You will be prompted with the familiar the open/save dialog box.

Thats all.
Sources: PHP Manual http://in2.php.net/manual/en/function.header.php

Would like to read your comments on this article and you are welcome in case of any query.

Related Posts

FAQ, php

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

11 Responses to “How to allow users to download files in PHP”

Leave Comment

(required)

(required)


10,907 spam comments
blocked by
Akismet