Pure PHP multiple file upload

This example is a PHP, suitable for learning, the cases can be added to the database code

Please select multiple files upload multiple files at once time, support doc jpg PDF etc.

There are a lot of this station inside the relatively practical multi file upload, here recommended a "jQuery Ajax not upload pictures to refresh and record to the database


Pure PHP upload multiple files
Demonstration

PHP Code
  1. <?php
  2. if(isset($_FILES['files'])){
  3. $res = upload_multiple_file($_FILES['files'],"../upload");
  4. echo $res;
  5. }
  6. function upload_multiple_file($file,$file_dir="../upload") {
  7. $overwrite=0;
  8. $allowed_file_type= array("pdf","ppt","pptx","xls","xlxs","doc","docx","jpg", "jpeg", "png", "gif");
  9. $max_file_size = 2097152;
  10. foreach($_FILES['files']['name'] as $fkey=> $fname){
  11. $ext = pathinfo($fname, PATHINFO_EXTENSION);
  12. if (!in_array($ext, $allowed_file_type)) {
  13. return "unsupported file format";
  14. break;
  15. }
  16. }
  17. foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
  18. $file_name = $_FILES['files']['name'][$key];
  19. $file_size =$_FILES['files']['size'][$key];
  20. $file_tmp_name =$_FILES['files']['tmp_name'][$key];
  21. $file_type=$_FILES['files']['type'][$key];
  22. if($file_size >0) {
  23. if($file_size > $max_file_size){
  24. $fsize=$max_file_size/1048576;
  25. return 'File size must be less than '.$fsize.' MB';
  26. break;
  27. }
  28. }
  29. if(is_dir($file_dir)==false){
  30. $status = mkdir("$file_dir", 0700);
  31. if($status <1){
  32. return "unable to create diractory $file_dir ";
  33. }
  34. }
  35. if(is_dir($file_dir)){
  36. if($overwrite <1){
  37. move_uploaded_file($file_tmp_name,"$file_dir/".$file_name);
  38. }
  39. }
  40. // $file_upload_query="INSERT into user_uploads (`u_id`,`file_name`,`file_type`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
  41. //mysql_query($file_upload_query);
  42. }
  43. return "Success";
  44. }
  45. ?>
  46. <form action="" method="POST" enctype="multipart/form-data">
  47. <input type="file" name="files[]" multiple/>
  48. <input type="submit" value="Upload"/>
  49. </form>



The original address

Posted by Sam at December 04, 2013 - 10:35 AM