jesobreira

multiple upload

Apr 4th, 2016
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. table:
  2. id int AUTO_INCREMENT
  3. filename VARCHAR(255)
  4. path VARCHAR(255)
  5.  
  6. form.html:
  7.  
  8. <form method="post" enctype="multipart/form-data">
  9. <input type="file" name="files[]" /> <!-- do not forget the [] in the name, it tells that it is an array -->
  10. </form>
  11.  
  12. upload.php OPTION 1:
  13.  
  14. <?php
  15. include 'yourmysqlorwhatever.php';
  16. /*
  17. Here's how $_FILES['files'] looks like:
  18. Array
  19. (
  20. [name] => Array
  21. (
  22. [0] => foo.txt
  23. [1] => bar.txt
  24. )
  25.  
  26. [type] => Array
  27. (
  28. [0] => text/plain
  29. [1] => text/plain
  30. )
  31.  
  32. [tmp_name] => Array
  33. (
  34. [0] => /tmp/phpYzdqkD
  35. [1] => /tmp/phpeEwEWG
  36. )
  37.  
  38. [error] => Array
  39. (
  40. [0] => 0
  41. [1] => 0
  42. )
  43.  
  44. [size] => Array
  45. (
  46. [0] => 123
  47. [1] => 456
  48. )
  49. )
  50. */
  51.  
  52. // Get how many files were sent
  53. $j = sizeof($_FILES['files']['name']-1;
  54.  
  55. for($i = 0; $i <= $j; $i++) {
  56. $filename = $_FILES['files']['name'][$i];
  57. $ext = strtolower(end(explode(".", $_FILES['files']['name'][$i])));
  58. if(in_array($ext, $allowed_ext)) {
  59. $path = "somefolder/".uniqid().".".$ext;
  60. move_uploaded_files($_FILES['files']['tmp_name'][$i], $path);
  61. your_sql_query_function("INSERT INTO yourtable (`filename`, `path`) VALUES ('$filename', '$path');");
  62. echo "File $filename uploaded.<br/>";
  63. } else {
  64. echo "File $filename not allowed.<br/>";
  65. }
  66. }
  67.  
  68.  
  69. upload.php OPTION 2 (cleaner):
  70. <?php
  71. include 'yourmysqlorwhatever.php';
  72.  
  73. /*
  74. Let's use this function to change how $_FILES['file'] is:
  75. */
  76. function reArrayFiles(&$file_post) {
  77.  
  78. $file_ary = array();
  79. $file_count = count($file_post['name']);
  80. $file_keys = array_keys($file_post);
  81.  
  82. for ($i=0; $i<$file_count; $i++) {
  83. foreach ($file_keys as $key) {
  84. $file_ary[$i][$key] = $file_post[$key][$i];
  85. }
  86. }
  87.  
  88. return $file_ary;
  89. }
  90.  
  91. // now we do:
  92. $files = reArrayFiles($_FILES['files']);
  93.  
  94. foreach($files as $file) {
  95. $filename = $file['name'];
  96. $ext = strtolower(end(explode(".", $filename)));
  97. if(in_array($ext, $allowed_ext)) {
  98. $path = "somefolder/".uniqid().".".$ext;
  99. move_uploaded_files($file['tmp_name'], $path);
  100. your_sql_query_function("INSERT INTO yourtable (`filename`, `path`) VALUES ('$filename', '$path');");
  101. echo "File $filename uploaded.<br/>";
  102. } else {
  103. echo "File $filename not allowed.<br/>";
  104. }
  105. }
Add Comment
Please, Sign In to add comment