Posted By

zitoloco on 03/25/10


Tagged

file upload


Versions (?)

Upload de arquivo


 / Published in: PHP
 

Função muito boa criada por Sean Nall.

  1. <?php
  2. # Written by Sean Nall <all.marx {at} gmail>
  3. # and placed into the public domain.
  4.  
  5. # @function upload_file
  6. #
  7. # @param $field string the name of the file upload form field
  8. # @param $dirPath string the relative path to which to store the file (no trailing slash)
  9. # @param $maxSize int the maximum size of the file
  10. # @param $allowed array an array containing all the "allowed" file mime-types
  11. #
  12. # @return mixed the files' stored path on success, false on failure.
  13. function upload_file($field = '', $dirPath = '', $maxSize = 100000, $allowed = array())
  14. {
  15. foreach ($_FILES[$field] as $key => $val)
  16. $$key = $val;
  17.  
  18. if ((!is_uploaded_file($tmp_name)) || ($error != 0) || ($size == 0) || ($size > $maxSize))
  19. return false; // file failed basic validation checks
  20.  
  21. if ((is_array($allowed)) && (!empty($allowed)))
  22. if (!in_array($type, $allowed))
  23. return false; // file is not an allowed type
  24.  
  25. do $path = $dirPath . DIRECTORY_SEPARATOR . rand(1, 9999) . strtolower(basename($name));
  26. while (file_exists($path));
  27.  
  28. if (move_uploaded_file($tmp_name, $path))
  29. return $path;
  30.  
  31. return false;
  32. }
  33. ?>
  34.  
  35. DEMO:
  36. <?php
  37.  
  38. if (array_key_exists('submit', $_POST)) // form has been submitted
  39. {
  40. if ($filepath = upload_file('music_upload', 'music_files', 700000, array('audio/mpeg','audio/wav')))
  41. echo 'File uploaded to ' . $filepath;
  42. else
  43. echo 'An error occurred uploading the file... please try again.';
  44. }
  45. echo '
  46. <form method="post" action="' .$_SERVER['PHP_SELF']. '" enctype="multipart/form-data">
  47. <input type="file" name="music_upload" id="music_upload" />
  48. <input type="submit" name="submit" value="submit" />
  49. </form>
  50. ';
  51.  
  52. print_r($_FILES); // for debug purposes
  53.  
  54. ?>

Report this snippet  

You need to login to post a comment.