Page 1 of 1

downloading files with PHP

Posted: Tue Nov 10, 2009 4:44 am
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:

Re: downloading files with PHP

Posted: Tue Nov 10, 2009 10:06 am
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