PHPGurukul

How to upload and validate a image in php

In this tutorial I will explain how to upload a image and how to validate image extension
Create an HTML form with two text field :

  • One is for Image title with input type text.
  • Second one is for upload image with input type file.For file upload input must be file(type=”file”). This input type show the file select control.

  • HTML form must have following attributes :

    • method=”post”
    • enctype=”multipart/form-data” (The enctype attribute specifies how the form-data should be encoded when submitting it to the server.)

    without these attributes , the image upload will not work.

    <form name="uploadimage"  enctype="multipart/form-data" method="post">
    <table width="100%"  border="0">
    <tr>
    <th width="26%" height="60" scope="row">Image Title:</th>
    <td width="74%"><input type="text" name="imagetitle"  autocomplete="off" class="form-control" required /></td>
    </tr>
    <tr>
    <th height="60" scope="row">Upload Image :</th>
    <td><input type="file" name="image"  required /></td>
    </tr>
    <tr>
    <th height="60" scope="row">&nbsp;</th>
    <td><input type="submit" value="Submit" name="submit" class="btn-primary" /></td>
    </tr>
    </table>
    </form>
    

    Create a database with name imagesdata. Inside this database we create a table with name tblimages.
    SQL Script for tblimages—

    CREATE TABLE IF NOT EXISTS `tblimages` (
      `id` int(11) NOT NULL,
      `ImagesTitle` varchar(120) DEFAULT NULL,
      `Image` varchar(150) DEFAULT NULL,
      `PostingDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
    

    Now create a database connection file(config.php)

    <?php
    define('DB_SERVER','localhost');
    define('DB_USER','root');
    define('DB_PASS' ,'');
    define('DB_NAME', 'imagesdata');
    $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
    // Check connection
    if (mysqli_connect_errno())
    {
     echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    ?>
    

    PHP Script for getting posted  values,  image validation, move images into directory and  insertion data into database

    <?php
    include_once("config.php");
    if(isset($_POST['submit']))
    {
    // Posted Values
    $imgtitle=$_POST['imagetitle'];
    $imgfile=$_FILES["image"]["name"];
    // get the image extension
    $extension = substr($imgfile,strlen($imgfile)-4,strlen($imgfile));
    // allowed extensions
    $allowed_extensions = array(".jpg","jpeg",".png",".gif");
    // Validation for allowed extensions .in_array() function searches an array for a specific value.
    if(!in_array($extension,$allowed_extensions))
    {
    echo "<script>alert('Invalid format. Only jpg / jpeg/ png /gif format allowed');</script>";
    }
    else
    {
    //rename the image file
    $imgnewfile=md5($imgfile).$extension;
    // Code for move image into directory
    move_uploaded_file($_FILES["image"]["tmp_name"],"uploadeddata/".$imgnewfile);
    // Query for insertion data into database
    $query=mysqli_query($con,"insert into tblimages(ImagesTitle,Image) values('$imgtitle','$imgnewfile')");
    if($query)
    {
    echo "<script>alert('Data inserted successfully');</script>";
    }
    else
    {
    echo "<script>alert('Data not inserted');</script>";
    }}
    }
     ?>
    

    Demo——————————————-

    View Demo

    How to run this script 

    1. Download the zip
    2. Extract zip file and put in the root directory
    3. open phpmyadmin. Create a db imagesdata then import SQL file(given inside the package)

    Download full source Code(How to upload and validate a image in php)
    Size: 28 KB
    Version: V 1.0

    Anuj Kumar

    This is Anuj Kumar. I’m a professional web developer with 4+ year experience. I write blogs in my free time. I love to learn new technologies and share with others.
    I founded PHPGurukul in September 2015. The main aim of this website to provide PHP, Jquery, MySQL, PHP Oops and other web development tutorials.
    .

    Recommended Tutorials for you


    Add comment

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Web Hosting with a FREE domain. On sale ₹99.00/mo

    Follow us

    Don't be shy, get in touch. We love meeting interesting people and making new friends.