How to Upload a File in PHP

File upload is quite easy and compact in PHP. We can upload a single or multiple files in PHP with just a few lines of code.

PHP can handle uploaded files in POST requests with below constants.

Read Also: PHP Multiple File Upload Using AJAX

File Upload Using PHP

Step 1: Create HTML Form To Upload File

In this step, we create a form to upload a file in PHP.

<!DOCTYPE html>
<html>
  <body>
    <form action="upload_handle.php" method="post" enctype="multipart/form-data">  
      <label>Select File to Upload:</label>  
      <input type="file" name="file"/>  
      <input type="submit" name="submit"/>  
    </form>
  </body>
</html>

NOTE: enctype=”multipart/form-data” is required to upload files in PHP via POST request in forms.

Step 2: Create a PHP file to handle the Uploaded File

In this step, we create a new PHP file named upload_handle.php to handle the uploading process via PHP. Please read our article on $_FILES to understand the uploading process.

<?php  
$target_path = "YOUR_PATH";  
$target_path = $target_path.basename( $_FILES['file']['name']);   
  
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {  
    echo "File uploaded successfully...";  
} else{  
    echo "Error, file not uploaded...";  
}  
?>

Explanation

  • We first define the $target_path variable where we want to store the uploaded file.
  • After that, we concatenate it with the original filename of the uploaded file which we found using basename() function.
  • Finally, we use the move_uploaded_file() function of PHP to move the uploaded file to our destination folder.Β 

Read Also: move_uploaded_file() function in PHP

Conclusion

In the above article, we learned the file upload process in PHP. We can upload any file via the above code to our server.

Enjoy Coding πŸ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
Scroll to top of the page using jQuery
Scroll to Top of the Page Using jQuery

Here is the simple example to scroll to top of the page with jQuery. HTML code jQuery Code Also read:...

Close