How To

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 🙂

Nachiket Panchal

Founder & Administrator of `errorsea` Having interest in Programming & Technology.

Recent Posts

5 Important Things To Know About WordPress Before You Use It

There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…

3 years ago

How to Install MySQL on Your PC in 3 Easy Steps

In this tutorial, I'm going to show you how to install MySQL on your computer.…

5 years ago

Download and Install Turbo C++ for Windows 10 (Full Installation Guide)

Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…

5 years ago

PHP .HTACCESS Redirects

We can redirect any webpage to any other or redirect the whole domain or website…

5 years ago

PHP Redirect Pages

There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…

5 years ago

PHP Include & Required

Include files in PHP are used in appending various global or config files. We can…

5 years ago