php file upload


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. // Configuration - Your Options
  3. $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
  4. $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
  5. $upload_path = './files/'; // The place the files will be uploaded to (currently a 'files' directory).
  6.  
  7. $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
  8. $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
  9.  
  10. // Check if the filetype is allowed, if not DIE and inform the user.
  11. if(!in_array($ext,$allowed_filetypes))
  12. die('The file you attempted to upload is not allowed.');
  13.  
  14. // Now check the filesize, if it is too large then DIE and inform the user.
  15. if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
  16. die('The file you attempted to upload is too large.');
  17.  
  18. // Check if we can upload to the specified path, if not DIE and inform the user.
  19. if(!is_writable($upload_path))
  20. die('You cannot upload to the specified directory, please CHMOD it to 777.');
  21.  
  22. // Upload the file to your specified path.
  23. if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
  24. echo 'Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>'; // It worked.
  25. else
  26. echo 'There was an error during the file upload. Please try again.'; // It failed :(.
  27.  
  28. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.