How to Upload Only PDF File with 2MB Size Validation

How to Upload Only PDF File with 2MB Size Validation

File Upload Validation is very important in web development to get rid of spammers. Mostly Spammers or bots upload irrelevant files or big files to disturb your website, if we do not use file validation; that’s the main reason to use file validation. Here in this we will learn how to validate extension of file and size of file.

Example:  Allowed only 2MB file and (.pdf) extension.

<?php
   if(isset($_FILES['image']))
   {
    $upload="";
              $file_name = $_FILES['image']['name'];
      $file_size =$_FILES['image']['size'];
      $file_tmp =$_FILES['image']['tmp_name'];
      $file_type=$_FILES['image']['type'];
      $file_ext=explode('.',$_FILES['image']['name']);
      
 
     
      if($file_ext[1]!="pdf" && $file_size > 2097152)
              {
                          move_uploaded_file($file_tmp,"uploads/".$file_name);
                          $upload='<div class="alert alert-success">
    <strong>Success!</strong> File Upload Successfully.
  </div>';
      }
     
      else
              {
                          $upload=' <div class="alert alert-danger">
    <strong>Error:</strong> File Extension should be .pdf or File Size less than 2MB.
  </div>';
              }                      
             
             
             
   }
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PDF File Upload Validation</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
   <body>
     
              <div class="container">
              <div class="row">
              <div class="col-lg-12">
              <?php
              if(!empty($upload))
              {
              echo $upload;
      }
              ?>
      <form action="" method="POST" enctype="multipart/form-data">
         <input type="file" class="form-control" name="image" />
         <input type="submit"/>
      </form>
             
              </div>
              </div>
              </div>
     
   </body>
</html>