Live Image Upload using jQuery, PHP and MySQL

Live image upload feature makes web application more user-friendly. With live upload, the user can select and upload images without page refresh. Also, once the image is uploaded the preview shows the user which helps to update image without navigation to another page. You can implement live image upload feature with jQuery without using Ajax or any plugin.

The live image upload is very useful in user panel to update profile picture. In this tutorial, we will show the live image upload and user profile picture update functionality. You’ll learn how to upload and update image without page refresh using jQuery, PHP, and MySQL.

In our example script, we’ll fetch a particular user data from the MySQL database and show the user details on the web page. The user can change the profile picture without page refresh and their profile image will be updated in the database instantly.

Database Table Creation

Here the simple users table structure that holds the basic profile information.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect to the MySQL database using PHP. You have to specify the database host ($dbHost), username($dbUsername), password ($dbPassword), and name ($dbName).

<?php
//DB details
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword '';
$dbName 'codexworld';

//Create connection and select DB
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

if(
$db->connect_error){
    die(
"Unable to connect database: " $db->connect_error);
}

Live Image Upload (index.php)

Initially, the user’s name and the image will be displayed. Once the user moves the cursor over the profile picture, an edit icon will be shown. By the clicking on the edit icon, the user can select an image to update profile picture. The selected image will be uploaded to the server and profile picture name is updated in the database using the upload.php file. On completion of image upload, the profile picture will be replaced by the newly uploaded image and it will be shown to the user.

HTML & PHP Code:
The following HTML is used to display user’s name and image with update option.

<?php
//Include database configuration file
include_once 'dbConfig.php';

//Get current user ID from session
$userId $_SESSION['user_id'];

//Get user data from database
$result $db->query("SELECT * FROM users WHERE id = $userId");
$row $result->fetch_assoc();

//User profile picture
$userPicture = !empty($row['picture'])?$row['picture']:'no-image.png';
$userPictureURL 'uploads/images/'.$userPicture;
?> <div class="container"> <div class="user-box"> <div class="img-relative"> <!-- Loading image --> <div class="overlay uploadProcess" style="display: none;"> <div class="overlay-content"><img src="images/loading.gif"/></div> </div> <!-- Hidden upload form --> <form method="post" action="upload.php" enctype="multipart/form-data" id="picUploadForm" target="uploadTarget"> <input type="file" name="picture" id="fileInput" style="display:none"/> </form> <iframe id="uploadTarget" name="uploadTarget" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe> <!-- Image update link --> <a class="editLink" href="javascript:void(0);"><img src="images/edit.png"/></a> <!-- Profile image --> <img src="<?php echo $userPictureURL?>" id="imagePreview"> </div> <div class="name"> <h4><?php echo $row['name']; ?></h3> </div> </div> </div>

JavaScript Code:
At first, include the jQuery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

The following jQuery handles the image upload and update functionality.

<script type="text/javascript">
$(document).ready(function () {
    //If image edit link is clicked
    $(".editLink").on('click', function(e){
        e.preventDefault();
        $("#fileInput:hidden").trigger('click');
    });

    //On select file to upload
    $("#fileInput").on('change', function(){
        var image = $('#fileInput').val();
        var img_ex = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
        
        //validate file type
        if(!img_ex.exec(image)){
            alert('Please upload only .jpg/.jpeg/.png/.gif file.');
            $('#fileInput').val('');
            return false;
        }else{
            $('.uploadProcess').show();
            $('#uploadForm').hide();
            $( "#picUploadForm" ).submit();
        }
    });
});

//After completion of image upload process
function completeUpload(success, fileName) {
    if(success == 1){
        $('#imagePreview').attr("src", "");
        $('#imagePreview').attr("src", fileName);
        $('#fileInput').attr("value", fileName);
        $('.uploadProcess').hide();
    }else{
        $('.uploadProcess').hide();
        alert('There was an error during file upload!');
    }
    return true;
}
</script>

Upload & Update Image (upload.php)

In the upload.php file, the image that posted from index.php file is uploaded to the server using PHP. Also, the existing profile picture name will update with the newly uploaded image name in the MySQL database using PHP. On completion of file upload, the completeUpload() function is loaded with status.

<?php
if(!empty($_FILES['picture']['name'])){
    
//Include database configuration file
    
include_once 'dbConfig.php';
    
    
//File uplaod configuration
    
$result 0;
    
$uploadDir "uploads/images/";
    
$fileName time().'_'.basename($_FILES['picture']['name']);
    
$targetPath $uploadDir$fileName;
    
    
//Upload file to server
    
if(@move_uploaded_file($_FILES['picture']['tmp_name'], $targetPath)){
        
//Get current user ID from session
        
$userId 1;
        
        
//Update picture name in the database
        
$update $db->query("UPDATE users SET picture = '".$fileName."' WHERE id = $userId");
        
        
//Update status
        
if($update){
            
$result 1;
        }
    }
    
    
//Load JavaScript function to show the upload status
    
echo '<script type="text/javascript">window.top.window.completeUpload(' $result ',\'' $targetPath '\');</script>  ';
}

style.css

The following CSS are used in live image upload to look good.

.container{width: 100%;}
.user-box {
    width: 200px;
    border-radius: 0 0 3px 3px;
    padding: 10px;
    position: relative;
}
.user-box .name {
    word-break: break-all;
    padding: 10px 10px 10px 10px;
    background: #EEEEEE;
    text-align: center;
    font-size: 20px;
}
.user-box form{display: inline;}
.user-box .name h4{margin: 0;}
.user-box img#imagePreview{width: 100%;}

.editLink {
    position:absolute;
    top:28px;
    right:10px;
    opacity:0;
    transition: all 0.3s ease-in-out 0s;
    -mox-transition: all 0.3s ease-in-out 0s;
    -webkit-transition: all 0.3s ease-in-out 0s;
    background:rgba(255,255,255,0.2);
}
.img-relative:hover .editLink{opacity:1;}
.overlay{
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 2;
    background: rgba(255,255,255,0.7);
}
.overlay-content {
    position: absolute;
    transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    top: 50%;
    left: 0;
    right: 0;
    text-align: center;
    color: #555;
}
.uploadProcess img{
    max-width: 207px;
    border: none;
    box-shadow: none;
    -webkit-border-radius: 0;
    display: inline;
}

Conclusion

For demonstration purpose, we’ve used live image upload functionality for profile picture update. However, you can use this functionality to any kind of image upload or update. In jQuery code, the file type is validated before upload, presently it accepts only .jpg or .jpeg or .png or .gif file type. Add or remove the file extension as per your requirement.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

2 Comments

  1. Frank O. Said...
  2. Khedar Said...

Leave a reply

keyboard_double_arrow_up