Enabling image preview while uploading images can be a great feature for the user experience.

Features of the proposed project

Update profile side

  1. upload image
  2. update bio

User profile

In this project, we will develop a form that accepts two different inputs: which are the user's biography and profile image. Once the user fills the input form and clicks on the upload button, the PHP script will get the form values which are the image and biography, and save the image inside our already created folder called "images". As soon as the image input is saved in the project folder called "images", a record that contains the image name and user's biography will be stored in the database created.

After all the information has been saved to the database, we will then create another page/file that will query the user's profile information from the database and display the image and biography respectively.

Let's do some work.
Create a project folder and call it image-preview. Inside this folder, create a file called update.php and a folder called images for storing all the images input by the user. Copy the below codes and paste there
On the first line of our update.php file, we are including a file that contains our PHP script responsible for receiving the form values and processing them (that is, saving the image in the images folder and creating a corresponding record in the user's table in the database).

update.php:

 

<?php include_once('controller.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>G7conet image preview and upload</title>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" />
  <link rel="stylesheet" href="css/main.css">
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-4 offset-md-4 form-div">
        <br>
        <center><a class="btn btn-primary" href="index.php">View all profiles</a></center>
        <form action="update.php" method="post" enctype="multipart/form-data">
          <h2 class="text-center mb-3 mt-3">Update profile</h2>
          <?php if (!empty($msg)): ?>
            <div class="alert <?php echo $msg_class ?>" role="alert">
              <?php echo $msg; ?>
            </div>
          <?php endif; ?>
          <div class="form-group text-center" style="position: relative;" >
            <span class="img-div">
              <div class="text-center img-placeholder"  onClick="triggerClick()">
                <h4>Upload image</h4>
              </div>
              <img src="images/avatar.jpg" onClick="triggerClick()" id="profileDisplay">
            </span>
            <input type="file" name="profileImage" onChange="displayImage(this)" id="profileImage" class="form-control" style="display: none;">
            <label>Profile Image</label>
          </div>
          <div class="form-group">
            <label>Bio</label>
            <textarea name="bio" class="form-control"></textarea>
          </div>
          <div class="form-group">
            <button type="submit" name="save_profile" class="btn btn-primary btn-block">Save User</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</body>
</html>
<script src="js/scripts.js"></script>

We are going to create our CSS file main.css for styling and beautifying the project. Create a folder called CSS in the root folder of our project and inside the CSS folder create a file called main.css and save the below codes in there.

main.css:

 

.form-div { margin-top: 100px; border: 1px solid #e0e0e0; }
#profileDisplay { display: block; height: 210px; width: 60%; margin: 0px auto; border-radius: 10%; }
.img-placeholder {
  width: 60%;
  color: white;
  height: 100%;
  background: #d96438;
  opacity: .7;
  height: 210px;
  border-radius: 10%;
  z-index: 2;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: none;
}
.img-placeholder h4 {
  margin-top: 40%;
  color: white;
}
.img-div:hover .img-placeholder {
  display: block;
  cursor: pointer;
}

Now let us add the Javascript. The Javascript is responsible for triggering the file input element and then also displaying the image for preview. Create a folder called js in the root folder of our project and inside the js folder create a file called scripts.css and save the below codes in there.

script.js:

 

function triggerClick(e) {
  document.querySelector('#profileImage').click();
}
function displayImage(e) {
  if (e.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e){
      document.querySelector('#profileDisplay').setAttribute('src', e.target.result);
    }
    reader.readAsDataURL(e.files[0]);
  }
}


When the user hovers on the rectangular box and clicks on the orange image area, he will be directed to select an image. After that, the image will be stored temporarily for the user to preview. The user can now add some biography to the form.  
When the user clicks the 'Save User' button, the input form will be submitted to the same page. So on that same update.php page, we are including a controller.php file that contains the code to process our form. This code receives the input values that were submitted from the form by the user.
In the root folder of the project create a file and name it controller.php;

controller.php:

 

<?php
  $msg = "";
  $msg_class = "";
  $conn = mysqli_connect("localhost", "root", "", "image_preview");
  if (isset($_POST['save_profile'])) {
    // for the database
    $bio = stripslashes($_POST['bio']);
    $profileImageName = time() . '-' . $_FILES["profileImage"]["name"];
    // For image upload
    $target_dir = "images/";
    $target_file = $target_dir . basename($profileImageName);
    // VALIDATION
    // validate image size. Size is calculated in Bytes
    if($_FILES['profileImage']['size'] > 2000000) {
      $msg = "Image size should not be greated than 2mb";
      $msg_class = "alert-danger";
    }
    // check if file exists
    if(file_exists($target_file)) {
      $msg = "File already exists";
      $msg_class = "alert-danger";
    }
    // Upload image only if no errors
    if (empty($error)) {
      if(move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target_file)) {
        $sql = "INSERT INTO user SET profile_image='$profileImageName', bio='$bio'";
        if(mysqli_query($conn, $sql)){
          $msg = "Profile updated successfully!";
          $msg_class = "alert-success";
        } else {
          $msg = "There was an error in the database";
          $msg_class = "alert-danger";
        }
      } else {
        $error = "There was an erro uploading the file";
        $msg = "alert-danger";
      }
    }
  }
?>

Before we forget, we need to create our database. If you notice in the code above we are connecting to a database called image-preview. Now create this database (image-preview) and create a table called user with the following fields:

user table:

 

CREATE TABLE `users` (
 `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
 `profile_image` varchar(255) NOT NULL,
 `bio` text NOT NULL
)

To display Image and bio from Database.
Once our image and bio are in the database, displaying it won't be a problem. Create a file in the root folder and name it index.php.
This file connects to the database, it queries all information from the user table and lists the user information in a tabular format thereby displaying each user's image and bio respectively.

index.php: 

 

<?php
  $conn = mysqli_connect("localhost", "root", "", "image_preview");
  $results = mysqli_query($conn, "SELECT * FROM user");
  $users = mysqli_fetch_all($results, MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>G7conet image preview and upload</title>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" />
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-4 offset-md-4" style="margin-top: 30px;">
        <a href="update.php" class="btn btn-primary">New profile</a>
        <br>
        <br>
        <table class="table table-bordered">
          <thead>
            <th>Image</th>
            <th>Bio</th>
          </thead>
          <tbody>
            <?php foreach ($users as $user): ?>
              <tr>
                <td> <img src="<?php echo 'images/' . $user['profile_image'] ?>" width="90" height="90" alt=""> </td>
                <td> <?php echo $user['bio']; ?> </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</body>
</html>

Note: You can download the full source code and do the installation yourself.

Requirements

  1. Download and Install any local web server such as XAMPP/WAMP.
  2. Download the provided source code zip file. (download button is located below)

Installation/Setup

  1. Open your XAMPP/WAMP's Control Panel and start Apache and MySQL.
  2. Extract the downloaded source code zip file.
  3. If you are using XAMPP, copy the image_preview folder from the extracted source code folder and paste it into the XAMPP's "htdocs" directory. And If you are using WAMP, paste it into the "www" directory.
  4. Open your XAMPP/WAMP PHPMyAdmin in a browser and create a new database naming image_preview.
  5. Import the provided SQL file into your newly created database. The file is located inside the database folder and is known as user.sql.
  6. Browse the Image Preview System in a browser. i.e. http://localhost/image_preview.