PHP File Upload

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

File upload in PHP


In this page, we will discuss how file uploading is performed using PHP. For uploading files using PHP, we need to perform following tasks -

1. Set up an html page with a form using which we will upload the file.
2. Setup a PHP script to upload the file to the server as well as move the file to it's destination.
3. Inform the user whether the upload was successful or not.

Code :

  1. <html>  
  2. <body>  
  3. <form action="upload_file.php" method="post" enctype="multipart/form-data">  
  4. <label for="file">Filename:label>  
  5. <input type="file" name="file" id="file" size="20" /><br />  
  6. <input type="submit" name="submit" value="Submit" />  
  7. form>  
  8. body>  
  9. html>  
  10. php  
  11. if (file_exists("upload/" . $_FILES["file"]["name"]))  
  12. {  
  13. echo $_FILES["file"]["name"] . " already exists. ";  
  14. }  
  15. else  
  16. {  
  17. move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]);  
  18. echo "Stored in: " . "upload/" . $_FILES["file"]["name"];  
  19. }  
  20. ?>  


Code Explanation
$_FILES["uploaded_file"]["name"] The original name of the file uploaded from the user's machine.
$_FILES["uploaded_file"]["type"] The MIME type of the uploaded file. You can use different types for test files, images and video.
$_FILES["uploaded_file"]["size"] The size of the uploaded file in bytes.
$_FILES["uploaded_file"]["tmp_name"] The location in which the file is temporarily stored on the server.
$_FILES["uploaded_file"]["error"] An error code if  the file upload fails.

This way you can upload files to a web server. We encourage you to copy the codes above and try it on your computer or a web server.