How to upload file Upload in PHP

In this tutorial, we will learn How to Upload a File in PHP with an example.

File upload in php

Contents

HTML

Creating a index.php file. in it create a one file type element for select a file and a button to submit the form.

<div id="custom-form-box" class="col-md-12">
  <form id="" class="form" action="" method="post" enctype="multipart/form-data">
     <h3 class="text-center text-info">File upload in PHP</h3>
      <span ><?php echo  $message;?></span>                                                           
      <div class="form-group">
         <label for="username" class="text-info">Username:</label><br>
         <input type="file" id="file-upload" name="uploadedFile" class="form-control">
      </div>                       
      <div class="form-group submit_div">   

         <input type="submit" name="uploadBtn" class="btn btn-info btn-md" value="upload">
     </div>                      
  </form>                      
</div>

PHP

Create a upload folder to store image files.

Read file extension and Initialized valid extensions Array $valid_extensions.

Check if file extension exists in $valid_extensions Array or not. If exists then upload a file.

<?php
$message='';
if(isset($_FILES['uploadedFile']['name'])){
  // get upload file name
  $filename = $_FILES['uploadedFile']['name']; 
  // set upload loacation.
  $uploadlocation = 'upload/'.$filename;
  // Get file extensions
  $file_extension = pathinfo($uploadlocation, PATHINFO_EXTENSION);
  $file_extension = strtolower($file_extension);
  // Valid file extensions
  $valid_ext = array("pdf","doc","docx","jpg","png","jpeg","xls");
  $response = 0;
  //Check Valid file extensions
  if(in_array($file_extension,$valid_ext)){
  // Upload file
  if(move_uploaded_file($_FILES['uploadedFile']['tmp_name'],$uploadlocation)){
    $message = "file Uploaded!";
    }else{
      $message = "Something went wrong!";
    } 
  }else{
       $message = "Please select valid file type.";
  }
}
?>

Output

Download source code

One Comment

  1. The very next time I read a blog, I hope that it does not fail me as much as this one. I mean, Yes, it was my choice to read through, but I really believed you’d have something helpful to say. All I hear is a bunch of crying about something you can fix if you were not too busy looking for attention.

    February 21, 2022
    Reply

Leave a Reply

Your email address will not be published.