How to upload profile photo with preview in a PHP registration form

Adding a profile photo is very common in a user registration form. Using PHP and MySQL we can create a registration form with a profile photo upload. Photo will be uploaded in the server and image file name can be stored in the database along with user details.

In this topic, we will see how we can upload an image with preview and store the image file name in the database using PHP and MySQL. You may use it for profile photo or for any other purposes where you want to upload a single image, like a product or an item. Here, we will create a simple user registration form where users can select his/her photo, preview the photo and upload it.

PHP upload image with previewAssumption

  1. You must have basic knowledge of PHP, HTML, CSS, JavaScript/jQuery.You can read below topics for more details:
    1. How to install xampp for Windows with setup for PHP development
    2. How to write PHP code with examples for beginners
    3. How to build a simple CRUD application in PHP and MySQL

upload image in php and mysql with previewFolders and Files

Upload image and save to a folder in php

We are using a folder named 'upload' under 'xampp/htdocs'.

  1. Folder 'cfg' - we are keeping database connection scripts dbconnect.php in this folder.
  2. Folder 'css' - custom stylesheet is in this folder
  3. Folder 'js' - custom JavaScript file is kept here
  4. Folder 'uploads' - uploaded photo is stored in this folder.
  5. index.php is the registration form.
  6. upload_photo.php is the PHP program which uploads photo in the server.

Below is the screenshot of the page:

Upload and Store Image in Database using PHP and mysql

Step 1 - Create a table in MySQL database to store photos

Create a table named 'user_profile' in MySQL database. This table will have user details, like name, email, photo etc. Table structure is given below:

File Uploading in PHP

Table has 4 columns.

  1. id - It is the unique id, primary key and auto incremented
  2. name - Name of the user
  3. email - email of the user
  4. image - Image file name of the photo of the user
Create table script for this table is given below, you can use this code to create the table. You can also download it from the download section of this topic.

user_profile.sql


CREATE TABLE `user_profile` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `image` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `user_profile`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `user_profile`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

After you create the table, verify if table structure is same as above.

Step 2 - Connect to MySQL database (dbconnect.php)

Use below script to connect to the database. We will include this in other programs where we need database connection.

dbconnect.php


<?php
  $server="localhost";
  $userid="root";
  $pwd="";
  $dbname="test";
  $conn = mysqli_connect($server, $userid, $pwd, $dbname);
//Check connection
if (!$conn) 
  	die("Connection Error: " . mysqli_connect_error());
?>

We are using mysqli_connect() method with 4 parameters.

  1. server - localhost
  2. userid - we are using root user
  3. password - no password for the user root
  4. database name - test in our case.

You can also read How to connect to MySQL database in PHP using MySQLi and PDO to know various ways to connect to MySQL database in PHP.

Step 3 - Develop a page for user registration with photo (index.php)

The registration page is a simple form where user can enter name, email id and select a profile photo. When form is submitted a row will be inserted in user_profile table with details of user and the image file will be uploaded in the server.

Php upload image to a directory

Let's see the code for index.php below:

index.php


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Registration</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link  rel="stylesheet" href="css/style.css">
</head>
<body>
  <div class="container">
	 	<?php 
	 	$name = $email = $file_name = $msg = "";
		$name_err = $email_err = $photo_err = "";
		include "upload_photo.php"; ?>
		<h2>Registration Form</h2>
		<div class="showMsg"><?php echo $msg;?></div>
		<form id ="frm" action = "index.php" method = "post" enctype="multipart/form-data">
				<div class="form-group col-md-12">
					 	<label>Name</label>
					 	<input type = "text" name="name" id = "name" class="form-control" maxlength="100"  value="<?php echo $name;?>" placeholder="Enter Your Name">
					 	<div class ="error"><?php echo $name_err;?></div>
				</div>
				<div class="form-group col-md-12">
					 	<label>Email</label>
					 	<input type = "text" name="email" id = "email" class="form-control"   value="<?php echo $email;?>" placeholder="Enter Your Email">
					 	<div class ="error"><?php echo $email_err;?></div>
				</div>
				<div class="form-group col-md-12">
					 <label for="photo">Your Photo</label>
					<div class="row">
						<div class="form-group col-md-7">
					     <p class="file">
					      <input type="file" name="photo" class="form-control" id="photo" value="<?php echo $photo;?>" onchange= "previewPhoto(this)">
					      <label for="photo">Select Photo</label>
					  	 </p>
					  	 <small color="blue">1) Max size: 2MB, File type: jpg, jpeg, png, bmp, gif. 2) No space in file name</small>
					      <div class ="error" id="imgErr"><?php echo $photo_err;?></div>
					  </div>
				      <div class="form-group col-md-5">
				      	<img id="prvwPhoto">
				      </div>
				  </div>
				</div>
				<div class="col-md-12 text-center">
			 		<input type ="submit" name="submit" class="btn btn-primary" value="Submit">
				</div>
		</form>
	</div>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	<script src="js/preview.js"></script>
</body>
</html>

upload_photo.php is included in the above code. This program is used to validate and upload the image.

You can see onChange event is used to call previewPhoto(), a JavaScript function. When a photo is selected this event will be triggered and preview of the photo will be displayed.

Step 4 - Write JavaScript/jQuery to preview photo (preview.js)

Preview Photo - Function previewPhoto()

Function previewPhoto() takes the input image file as parameter. Let's see the code for this function:

preview.js


// function to preview photo
function previewPhoto(input) {
    var regex = /^([a-zA-Z0-9\_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
    if (input.files && input.files[0]) {
        var image = input.files[0];
        if (regex.test(image.name.toLowerCase())) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $("#prvwPhoto").attr({'src':e.target.result,'width':'120','height':'100','title':input.files[0].name,'alt':'Profile Photo'});
            };
            reader.readAsDataURL(input.files[0]);
            $("#imgErr").html("");
        }
        else {
        alert(image.name + " is not a valid image file.");
        return false;
     }
    }
}

Image file extension must be only jpg, jpeg, gif, png and bmp. We are validating the image file name and then showing the preview.

Step 5 - Write PHP program to upload photo (upload_photo.php)

upload_photo.php will be executed when user submits the form. This program validates all inputs including photo. If all validations are successful, photo is uploaded and a row is inserted in user_profile table. Let's see the code:

upload_photo.php


<?php
// report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
include "cfg/dbconnect.php";
$upload_path = "uploads/";
$valid = true;

if (isset($_POST['submit'])) {
	$name  = trim($_POST['name']);
	$email = trim($_POST['email']);
	$photo = $_FILES["photo"]["name"];
	// validate fields
	if (empty($name)) {
		$name_err = "Name is required";
		$valid = false;
	}
	if (empty($email)) {
		$email_err = "Email is required";
		$valid = false;
	}
	elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)){
			$email_err = "Not a valid email address";
			$valid = false;
		}
	else {
			// check if email already exists
    	$sql = "select * from user_profile where email = '$email'";
    	$rs = mysqli_query($conn,$sql);
    	if (mysqli_num_rows($rs) >0) {
        	$email_err = "Email id already registered.";
        	$valid = false;
    	}
	}
	if (empty($photo)) {
			$photo_err = "Photo is required";
	   	$valid = false;
    }
  else
    {  
    	$file_name = basename($_FILES["photo"]["name"]);
		  $tmp_file = $_FILES["photo"]["tmp_name"];
		  $image_name = time()."_".$file_name;
		  $target_file = $upload_path.$image_name;
		  $imageType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
		  // check file extension
		  if($imageType != "jpg" && $imageType != "png" && $imageType != "jpeg"
			&& $imageType != "gif" && $imageType != "bmp") {
			  $photo_err = "Error: Invalid file type";
			  $valid = false;
			}
    	//check if it is an image
		 if(exif_imagetype($tmp_file) != IMAGETYPE_GIF && exif_imagetype($tmp_file) != IMAGETYPE_JPEG && exif_imagetype($tmp_file) != IMAGETYPE_PNG && exif_imagetype($tmp_file) != IMAGETYPE_BMP) {
            $photo_err = "Error: File is not an Image file";
            $valid = false;
            }
		  // Check file size, max 2M
		  if ($_FILES["photo"]["size"] > 2000000) {
		    $photo_err = "Error: Image size exceeds 2MB";
		    $valid = false;
		  }
    }
	// if all validations are sucecssful, upload photo and insert into table
    if ($valid) {
			if (!move_uploaded_file($tmp_file, $target_file)) {
	          $msg = "Error: There was an error uploading photo.";
	        }
	    else { // upload photo is successful, insert row in database
	    	$insert = "insert into user_profile (name, email, image)  values ('$name','$email','$image_name')";
   			$result = mysqli_query($conn,$insert);
   			if(!$result) {  // database insert fails, delete uploaded photo 
   				if (file_exists($target_file)){
   					unlink($target_file);  
        		$msg = "Error in submission. Please contact Admin";
        	}
   			}
   			else { // all success
   				$msg = "Your Registration completed successfully";
   				$name = $email = "";
   			}
	    }
	   }
}

Set the upload directory in the server as "uploads/" where uploaded photos will be kept. There is a flag used named $valid, this is used for validation purpose.

For photo, there will be some additional validations - file extension, image type, image file size. If all validations are successful, it uploads the image file using move_uploaded_file() PHP function. A row containing name, email_id and image file name is inserted into the database table 'user_profile'. If database insert is not successful, we have to remove uploaded file. That is why we have used unlink() function in line 72 to remove the image file.

Step 6 - Add CSS (style.css)

We need to add some styles. Very simple and basic styles are used here. You can always add better styles. I have already added style.css in index.php. See below:

style.css


h2{
  margin-top: 20px;
  text-align: center;
}
.showMsg{
  width:auto;
  height: 20px;
  text-align: center;
  margin-bottom: 20px;
}
#frm{
  width:40%;
  margin:auto;
}
label{
    font-weight: bold;
  }
.success{
  color:green;
  height: 10px;
}
.error{
  color:red;
  height: 16px;
}
.file {
  position: relative;
      margin: 0;
}
.file label {
  background: #696969;
  padding: 12px 20px;
  color: #fff;
  font-weight: bold;
  font-size: .9em;
  transition: all .4s;
}
.file input {
  position: absolute;
  display: inline-block;
  left: 0;
  top: 0;
  opacity: 0.01;
  cursor: pointer;
}
.file input:hover + label,
.file input:focus + label {
  background: #34495E;
  color: #39D2B4;
}
.remove{
  cursor: pointer;
  padding-left: 11px;
  color: red;
}
@media (max-width: 600px){
#frm {
    width: 100%;
  }
}

Move_uploaded_file() function in phpTest the Application

In XAMPP control panel Apache and MySQL services should be running. Open the browser and run localhost/upload. You will see the home page as displayed below:

How to upload image in PHP

Enter name, email and select a photo and click on Submit button, Registration should be completed and you should see the message displayed. Verify in the database, see if row is inserted in user_profile table. Also check in 'uploads/' folder, photo should be uploaded.

This completes our development and testing. Hope you could understand all the steps and you could test it successfully.

How to upload and display image in PHPImportant Note

  1. For uploading images, you must verify below parameters in php.ini file. Below are the values set for these parameters in my php.ini

    
    ; Whether to allow HTTP file uploads.
    ; http://php.net/file-uploads
    file_uploads=On
    
    ; Maximum allowed size for uploaded files.
    ; http://php.net/upload-max-filesize
    upload_max_filesize=2M
    
    ; Maximum number of files that can be uploaded via a single request
    max_file_uploads=20
    
  2. You can use maximum allowed file size in your program by looking at the parameter as set in php.ini file. I have used 2M for example purpose, you can set it 4M or 6M or more.

PHP File UploadDownload Source Code

Image upload in php with exampleConclusion

This topic was for a single photo upload, a similar topic is written for multiple photos upload where you can select multiple photos and upload them. Please see the related topics below to see more on file upload in php.

Hope I could explain the steps properly. If you find it useful, you can use it in your project or in any other web application with similar requirement.