How to upload and save form image in PHP

Step 1:
Create database and table to save image file name

Query to create database:

CREATE DATABASE user_profile;

Query to create Table:

CREATE TABLE image_uploads(
	  upload_id int(11) NOT NULL AUTO_INCREMENT,
	  name varchar(255) NOT NULL,
	  profile_image varchar(255) NOT NULL,
	  PRIMARY KEY (upload_id)

Database Table structure:

Image upload database table structure

Step 2:

Create directory in your root and name it as “upload_image“.
Set read/write permission(777) to newly created directory.

upload image new directory

Step 3:

Create html form with file upload input and name it as “index.php

Image upload html

Step 4:

Create file “image-upload.php” and write database connection code and include this file in “index.php

Image upload Database connection

Step 5:

Code to upload image into server and store image name in database table.

Image upload PHP code


Upload Image and Name:

Image upload demo

Image upload demo step-2

List Uploaded Image:

List uploaded image

Stored Image data in Database:

Uploaded database record

Uploaded Image in server Location:

Uploaded Image in server location

Full code example:

Filename: “index.php


$currentPath = $_SERVER['PHP_SELF'];
$pathInfo = pathinfo($currentPath);

$baseUrl = "http://" . $_SERVER['HTTP_HOST'] . $pathInfo['dirname'].'/';
    <!DOCTYPE html>

        <link href="" rel="stylesheet" type="text/css">
        <script type="text/javascript" src=""></script>
        <script type="text/javascript" src=""></script>
            .fileUpload {
                position: relative;
                overflow: hidden;
                margin: 10px;
            .fileUpload input.upload {
                position: absolute;
                top: 0;
                right: 0;
                margin: 0;
                padding: 0;
                font-size: 20px;
                cursor: pointer;
                opacity: 0;
                filter: alpha(opacity=0);
        <script type="text/javascript">
            $(document).on("change", "#uploadBtn", function() {
                var filePath = $("#uploadBtn").val();
                if (filePath.match(/fakepath/)) {
                    filePath = filePath.replace(/C:\\fakepath\\/i, '');

                if (this.files && this.files[0]) {
                    var reader = new FileReader();
                    reader.onload = imageIsLoaded;

            function imageIsLoaded(e) {

            function removeImage(e) {
                $('#myImg').attr('src', '');



        <div class="vd_content-wrapper">
            <div class="vd_container">
                <div class="vd_content-section clearfix">
                    <h1 style="color: #FF4500;">Image Upload Demo</h1>
                    <div class="panel widget light-widget">

                        <form class="form-horizontal" action="image-upload.php" method="post" role="form" enctype="multipart/form-data">
                            <div class="col-md-6" style="padding-top:20px;">
                                <div class="form-group">
                                    <label class="control-label col-md-4">Name<span class="vd_red">*</span> </label>
                                    <div id="first-name-input-wrapper" class="controls col-md-6">
                                        <input type="text" class="width-120 Name required" name="name" id="name" value="" required>

                                <div class="form-group" id="uploadbanner">
                                    <label class="control-label col-md-4" style="padding-top:12px;">Upload Image: </label>
                                    <div id="website-input-wrapper" class="controls col-md-8">
                                        <input id="add-file" placeholder="Choose File" disabled="disabled" />
                                        <div class="fileUpload btn btn-primary">
                                            <span>Upload Image</span>
                                            <input id="uploadBtn" type="file" name="image" class="upload" />
                                        <img id="myImg" style="width:73%; float:left; display:none;" src="" alt="your image" />
                                        <a id="remove_promo_image" onclick="removeImage()" style="cursor:pointer; margin-left:20px; color:#d43f3a; font-size:20px; float:left; display:none; text-decoration:underline;">Remove</a>

                                <div class="form-group" style="text-align:center">
                                    <button class="btn" type="submit" style="background-color:#1fae66; color:#fff;">Submit</button>


                <div class="panel widget">
                    <div class="panel-heading vd_bg-grey">
                        <h3> <span class="menu-icon">Listing Uploaded Image:</h3>
                    <div class="panel-body table-responsive">
                        <table id="example" class="table table-hover display">
                                    <th style="width:15%">S.No</th>
                                    <th style="width:15%">Name</th>
                                    <th style="width:10%">Image</th>
                                    <th style="width:21%">Action</th>
						if (!empty($result)) {
							foreach ($result as $data) {
                                            <?php echo $data['upload_id'] ?>
                                            <?php echo $data['name'] ?>
                                        <td><img style="max-width:250px; max-height:200px;" src="<?php echo $baseUrl." upload_image/ ".$data['profile_image'] ?>" alt="profile image" /></td>
                                        <td><a href="#" data-original-title="delete" class="btn btn-danger small btnaction">Delete</a></td>





// connect database
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "user_profile";

$db = new mysqli($hostname, $username, $password, $dbname);

if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);

// image upload code
if (!empty($_POST['name'])) {
	$targetDir = "upload_image/";
	$targetFile = $targetDir . basename($_FILES["image"]["name"]);
	$extension = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
	$newFileName = rand(11111, 99999) . '.' . $extension;
	$newTargetFile = $targetDir . $newFileName;
	if (move_uploaded_file($_FILES["image"]["tmp_name"], $newTargetFile)) {
		$db->query("INSERT into image_uploads (name, profile_image) VALUES ('".$_POST['name']."', '".$newFileName."')");
	header("Location: index.php");

// data collection to listing
$query = $db->query("SELECT * FROM image_uploads");
$result = array();
if ($query->num_rows > 0) {
	while ($row = $query->fetch_assoc()) {
		$result[] = $row;

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *