How to Upload only jpeg,jpg and png Image in php

Sometimes we have to need to restrict our file upload to allowed only jpg, png files with size validation. It is mostly used in the gallery page, event page, and image sliders. If we properly validate our file input then it also helps us to keep away from spammers.

Example:  Allowed only (jpeg, jpg, png)  with  2MB  Size file.

<?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']);
      $extensions=array("jpeg","jpg","png");
     
if(in_array($file_ext[1],$extensions)===true && $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 .jpeg,jpg,png 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>  

Categories: web development php

Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 20 Days

Crash : 7 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 7 Month

Fastrack : 4 Month

Crash : 2 Month

Related Blogs

Request For Demo