downloading files with PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
urooj786
Forum Newbie
Posts: 12
Joined: Mon Nov 09, 2009 11:56 pm

downloading files with PHP

Post by urooj786 »

I have uploaded files with move_uploaded_file(); function in a folder named upload and now i want to download it in a specified folder how i do this plz suggests me????
:oops:
ceiroa
Forum Newbie
Posts: 11
Joined: Thu Oct 08, 2009 4:14 pm

Re: downloading files with PHP

Post by ceiroa »

To download a file from a publicly accessible folder (a folder below the web root) you just need to make a link to that file. You can have a static link of a dynamic link built with php.

Example of dynamic link:

Code: Select all

echo '<a href="'.$foldername.'/'.$filename.'">Click to Download</a>";
If the folder containing the file you want to download is above the web root you can have a link to a php file that includes something like this (this is for an XML file, but you'll have to set the headers properly for whatever type of file you are downloading):

Code: Select all

 
//Download file with xml header
header('Content-type: application/xml; charset="utf-8"',true);
header("Content-Disposition: attachment; filename=\"$filename\"");
$hand = fopen($file,"r");
fpassthru($hand);
fclose($hand);
 
You could pass it the file name and folder name as arguments if you wanted.

This code basically passes the contents of the file to the output buffer. The advantage here is that only the code will be able to access the file. You could control that only logged in users can access the file.

In both cases the user will choose which folder in her own computer she'd like to download the file to.
---------------
Carlos R. M. Eiroa
PHP Consultant
Post Reply