Posted By

vagrantradio on 08/31/10


Tagged

upload


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

googooster
brucegui
benediktvaldez


File Upload


 / Published in: PHP
 

  1. <?php
  2.  
  3. $max_filesize = 10000000; // Maximum filesize in BYTES.
  4. $allowed_filetypes = array('.pdf','.xls','.doc','.xlsx'); // These will be the types of file that will pass the validation.
  5. $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
  6. $file_strip = preg_replace("/[^a-zA-Z0-9.]/","",$filename); //Strip non-alphanumeric characters and leave file ext period
  7. $upload_path = '/path/to/uploads/'; //Set upload path
  8.  
  9. // Check if the filetype is allowed, if not DIE and inform the user.
  10. if(!in_array($ext,$allowed_filetypes)) {
  11. die('<div class="error">The file you attempted to upload is not allowed.</div>');
  12. }
  13. // Now check the filesize, if it is too large then DIE and inform the user.
  14. if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
  15. die('<div class="error">The file you attempted to upload is too large.</div>');
  16. }
  17. // Check if we can upload to the specified path, if not DIE and inform the user.
  18. if(!is_writable($upload_path)) {
  19. die('<div class="error">You cannot upload to the /uploads/ folder. The permissions must be changed.</div>');
  20. }
  21. // Move the file if eveything checks out.
  22. if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $file_strip)) {
  23. echo '<div class="success">'. $file_strip .' uploaded successfully</div>'; // It worked.
  24. } else {
  25. echo '<div class="error">'. $file_strip .' was not uploaded. Please try again.</div>'; // It failed :(.
  26. }
  27. ?>

Report this snippet  

You need to login to post a comment.