Skip to main content

PHP File Upload and Download Script

Here you will find file upload and download php script. First I have
provided the code you can use directly and then very important tips and
facts about each issues.

You will find detail descriptions of
parameters, both client and server side, affecting upload and download
of files. Example will show how to store MSWord file in database and
also how to upload PDF file to server. Change it little bit and it will
work for all types of files.

A. PHP File Upload Script

  1. <HTML>  
  2. <HEAD>  
  3. <TITLE> PHP File Upload Script </TITLE>  
  4. </HEAD>  
  5. <BODY>  
  6. <?php  
  7. if( isset($_POST['submit1'])) {  
  8. // $_FILES is the array auto filled when you upload a file and submit a form.  
  9. $userfile_name = $_FILES['file1']['name']; // file name  
  10. $userfile_tmp  = $_FILES['file1']['tmp_name']; // actual location  
  11. $userfile_size  = $_FILES['file1']['size']; // file size  
  12. $userfile_type  = $_FILES['file1']['type']; // mime type of file sent by browser. PHP doesn't check it.  
  13. $userfile_error  = $_FILES['file1']['error']; // any error!. get from here 
  14.  
  15. // Content uploading. 
  16. $file_data = ''; 
  17. if ( !empty($userfile_tmp)) 
  18. { 
  19. // We encode the data just to make it more database friendly 
  20. $file_data = base64_encode(@fread(fopen($userfile_tmp, 'r'), filesize($userfile_tmp) ) ); 
  21. } 
  22.  
  23. switch (true) 
  24. { 
  25. // Check error if any 
  26. case ($userfile_error == UPLOAD_ERR_NO_FILE): 
  27. case empty($file_data): 
  28. echo 'You must select a document to upload before you can save this page.'; 
  29. exit; 
  30. break; 
  31. case ($userfile_error == UPLOAD_ERR_INI_SIZE): 
  32. case ($userfile_error == UPLOAD_ERR_FORM_SIZE): 
  33. echo 'The document you have attempted to upload is too large.'; 
  34. break; 
  35.  
  36. case ($userfile_error == UPLOAD_ERR_PARTIAL): 
  37. echo 'An error occured while trying to recieve the file. Please try again.'; 
  38. break; 
  39.  
  40. } 
  41.  
  42. if( !empty($userfile_tmp)) 
  43. { 
  44. // only MS office and text file is accepted. 
  45. if( !(($userfile_type=="application/msword") || ($userfile_type=="text/plain")) ) 
  46. {echo 'Your File Type is:'. $userfile_type; 
  47. echo '<br>File type must be text(.txt) or msword(.doc).'; 
  48.  
  49. exit; 
  50. } 
  51. } 
  52. echo filesize($userfile_tmp); 
  53. } 
  54. ?> 
  55.  
  56. <form name="profile" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>" target="_self" enctype="multipart/form-data" >  
  57.   
  58. <P align ="center"><input type="hidden" name="MAX_FILE_SIZE" value="1000000">  
  59. <input type="file" name="file1" value="AttachFile" device="files" accept="text/*" tabindex=18 >  
  60.   
  61. <input type="submit" name="submit1" value="Submit" />  
  62. </P>  
  63.   
  64. </form>  
  65.   
  66. </BODY>  
  67. </HTML>  

Important Tips:

  • Form enctype="multipart/form-data"
  • MAX_FILE_SIZE - hidden input element with name=MAX_FILE_SIZE is used to check filesize in browser itself.
  • device="files" accept="text/*" - accept specifies mime types.
  • post_max_size, upload_max_filesize and memory_limit are php.ini settings.
  • post_max_size should be greater than upload_max_size.
  • If post_max_size is less than size of posted data then $_POST and $_FILES superglobals are empty.
  • max_input_time
    sets the max time in seconds, the script is allowed to receive input;
    this include file uploads. - also php.ini settings.
  • Check for
    enctype="multipart/form-data" in your form tag, if unavailable your file
    will not be available to your server. and you will see $_FILES empty.
  • Check name in your <input type="file">, if unavailable your $_FILES will again show nothing in it.

B. PHP File Download Script:

Download PDF file

  1. <?php  
  2. // your file to upload  
  3. $file = '2007_SalaryReport.pdf';  
  4. header("Expires: 0");  
  5. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");  
  6. header("Cache-Control: no-store, no-cache, must-revalidate");  
  7. header("Cache-Control: post-check=0, pre-check=0", false);  
  8. header("Pragma: no-cache");  
  9. header("Content-type: application/pdf");  
  10. // tell file size  
  11. header('Content-length: '.filesize($file));  
  12. // set file name  
  13. header('Content-disposition: attachment; filename='.basename($file));  
  14. readfile($file);  
  15. // Exit script. So that no useless data is output-ed.  
  16. exit;  
  17. ?>  

Generate data for Excel and prompt for Downloading Excel file

Sometimes
you want to give dynamically produced data to user. If you are giving
dynamically generated content data to user then you have to buffer all
your data until your all data is ready for download. If you do not do
this then your data will not output for download correctly. or probably
you will get lots of download pop-up.

  1. <?php  
  2. // file name to be appear in output name. User can change their file name  
  3. // but this will give him a option for file name.  
  4. $file = 'testExcelFile.xls';  
  5. // start buffring  
  6. ob_start();  
  7. // sample dynamically generated data  
  8. echo '<table border="1"> ';  
  9. echo '<tr><th>Name</th><th>Age</th></tr>';  
  10. for ($i=0; $i<=5; $i++) {     echo "<tr><td>Name$i</td><td>".($i+1)."</td></tr>";  
  11. }  
  12. echo '</table>';  
  13. $content = ob_get_contents();  
  14. ob_end_clean();  
  15. header("Expires: 0");  
  16. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");  
  17. header("Cache-Control: no-store, no-cache, must-revalidate");  
  18. header("Cache-Control: post-check=0, pre-check=0", false);  
  19. header("Pragma: no-cache");  
  20. header("Content-type: application/vnd.ms-excel;charset:UTF-8");  
  21. header('Content-length: '.strlen($content));  
  22. header('Content-disposition: attachment; filename='.basename($file));  
  23. // output all contents  
  24. echo $content;  
  25. exit// If any tags/things not supported by excel will output then it will try to //open in office word  
  26. ?>  

- Check data output. If you output any data to browser before header(); then header will not set.
- Check file permission if you are getting error in reading the file content.
- You must also provide link to file to be download to user so that
they can download your file if for any reason your download script is
not working.
<a href='http://satya61229.com/download/testfile123.pdf'>For downloading click here</a>
In this case your file will be downloaded using you provided link. The
file will be opened if your file type is associated/mapped in your users
browser. Otherwise they will pop-up for download.

You can download any file this way. Just change the content-type headers.
You need to change the content-type header to your file type (MIME Type).
Use application/vnd.ms-excel for excel file download,
appliacation/msword for MS Word file download. If you are not sure about
the file type then you can use
Content-Type:appliaction/octet-stream.

Information about How to upload large file.

Liked! So, share it.

Update: Thanks timmy for correcting the info about mime type.

Ref: http://www.satya-weblog.com/2007/05/php-file-upload-and-download-script....