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,
	  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
	  PRIMARY KEY (upload_id)
	) ENGINE=InnoDB;

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

Demo:

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

<?php
include('image-upload.php');

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

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

    <head>
        <link href="http://findsolutionshere.com/ref/css/bootstrap.min.css" rel="stylesheet" type="text/css">
        <script type="text/javascript" src="http://findsolutionshere.com/ref/js/jquery.js"></script>
        <script type="text/javascript" src="http://findsolutionshere.com/ref/js/bootstrap.min.js"></script>
        <style>
            .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);
            }
        </style>
        <script type="text/javascript">
            $(document).on("change", "#uploadBtn", function() {
                var filePath = $("#uploadBtn").val();
                if (filePath.match(/fakepath/)) {
                    filePath = filePath.replace(/C:\\fakepath\\/i, '');
                }
                $("#add-file").val(filePath);

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

            function imageIsLoaded(e) {
                $('#myImg').show();
                $('#myImg').attr('src', e.target.result);
                $('#remove_promo_image').show();
            }

            function removeImage(e) {
                $('#myImg').fadeOut();
                $('#remove_promo_image').fadeOut();
                $('#myImg').attr('src', '');
                $("#uploadBtn").val('');
                $("#add-file").val('');
            }
        </script>

    </head>

    <body>

        <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>
                                </div>

                                <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" />
                                        </div>
                                        <br/>
                                        <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>
                                </div>

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

                    </div>
                </div>

                <div class="panel widget">
                    <div class="panel-heading vd_bg-grey">
                        <h3> <span class="menu-icon">Listing Uploaded Image:</h3>
                    </div>
                    <div class="panel-body table-responsive">
                        <table id="example" class="table table-hover display">
                            <thead>
                                <tr>
                                    <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>
                                </tr>
                                <?php
						if (!empty($result)) {
							foreach ($result as $data) {
						?>
                                    <tr>
                                        <td>
                                            <?php echo $data['upload_id'] ?>
                                        </td>
                                        <td>
                                            <?php echo $data['name'] ?>
                                        </td>
                                        <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>
                                    </tr>
                                    <?php
							}
						}
						?>
                            </thead>
                        </table>
                    </div>
                </div>

            </div>
        </div>

    </body>

    </html>

Filename:image-upload.php

<?php
// 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 *