Code to upload a file in PHP


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

Code to upload a file in PHP


Copy this code and paste it in your HTML
  1. <?php
  2. if($_FILES['photo']['name'])
  3. {
  4. //if no errors...
  5. if(!$_FILES['file']['error'])
  6. {
  7. //now is the time to modify the future file name and validate the file
  8. $new_file_name = strtolower($_FILES['file']['tmp_name']); //rename file
  9. if($_FILES['file']['size'] > (1024000)) //can't be larger than 1 MB
  10. {
  11. $valid_file = false;
  12. $message = 'Oops! Your file\'s size is to large.';
  13. }
  14.  
  15. //if the file has passed the test
  16. if($valid_file)
  17. {
  18. //move it to where we want it to be
  19. move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$new_file_name);
  20. $message = 'File uploaded successfully.';
  21. }
  22. }
  23. //if there is an error...
  24. else
  25. {
  26. //set that to be the returned message
  27. $message = 'Something got wrong while uploading file: '.$_FILES['file']['error'];
  28. }
  29. }
  30.  
  31. ?>

URL: https://www.onlineinterviewquestions.com/code-to-upload-file-in-php/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.