How do I upload and download multiple type of files in PHP from MySQL database?

Posted by:

For upload

  1. <html lang=“en”>
  2. <head>
  3. <meta charset=“UTF-8” />
  4. <title>Multiple File Ppload with PHP</title>
  5. </head>
  6. <body>
  7. <form action=“” method=“post” enctype=“multipart/form-data”>
  8. <input type=“file” id=“file” name=“files[]” multiple=“multiple” accept=“image/*” />
  9. <input type=“submit” value=“Upload!” />
  10. </form>
  11. </body>
  12. </html>

PHP CODE

  1. $valid_formats = array(“jpg”, “png”, “gif”, “zip”, “bmp”);
  2. $max_file_size = 1024*100; //100 kb
  3. $path = “uploads/”; // Upload directory
  4. $count = 0;
  5. if(isset($_POST) and $_SERVER[‘REQUEST_METHOD’] == “POST”){
  6. // Loop $_FILES to exeicute all files
  7. foreach ($_FILES[‘files’][‘name’] as $f => $name) {
  8. if ($_FILES[‘files’][‘error’][$f] == 4) {
  9. continue; // Skip file if any error found
  10. }
  11. if ($_FILES[‘files’][‘error’][$f] == 0) {
  12. if ($_FILES[‘files’][‘size’][$f] > $max_file_size) {
  13. $message[] = “$name is too large!.”;
  14. continue; // Skip large files
  15. }
  16. elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
  17. $message[] = “$name is not a valid format”;
  18. continue; // Skip invalid file formats
  19. }
  20. else{ // No error found! Move uploaded files
  21. if(move_uploaded_file($_FILES[“files”][“tmp_name”][$f], $path.$name))
  22. $count++; // Number of successfully uploaded file
  23. }
  24. }
  25. }
  26. }

Download FIle

  1. <?php
  2. function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
  3. {
  4. $zip = new ZipArchive();
  5. if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
  6. exit(“cannot open <$archive_file_name>\n”);
  7. }
  8. foreach($file_names as $files)
  9. {
  10. $zip->addFile($file_path.$files,$files);
  11. //echo $file_path.$files,$files.”<br />”;
  12. }
  13. $zip->close();
  14. header(“Content-type: application/zip”);
  15. header(“Content-Disposition: attachment; filename=$archive_file_name”);
  16. header(“Pragma: no-cache”);
  17. header(“Expires: 0”);
  18. readfile(“$archive_file_name”);
  19. exit;
  20. }
  21. require_once(“config.php”);
  22. $cqurfetch=mysql_query(“SELECT * FROM albums where user_id=’$user_id’ and accept=’1′”);
  23. while($row = mysql_fetch_array($cqurfetch))
  24. {
  25. $file_names[] = $row[‘user_album_images’];
  26. }
  27. $archive_file_name=time().‘.gallery.zip’;
  28. $file_path=“/uploads/”;
  29. zipFilesAndDownload($file_names,$archive_file_name,$file_path);
  30. ?>
0

Add a Comment