How to upload, change and remove profile photo using Ajax in PHP

You can upload, change or delete an image using Ajax in PHP. You can add your photo as profile picture while updating user profile. In this topic, we will develop an application in PHP and MySQL to update user profile with photo. User can add/update/delete profile photo using PHP, MySQL and Ajax. This is also an example of image CRUD using Ajax in PHP..

We will be adding login and logout to this application just to get user information and update photo based on the user details.

I have few related topics you might be interested in, please see below:

  1. How to preview, upload and delete a photo without submitting a form in PHP, Ajax and MySQL
  2. How to upload a photo with preview in PHP and MySQL

upload profile image using PHP and ajaxAssumption

  1. You must have basic knowledge of PHP, HTML, CSS, JavaScript/jQuery and Ajax. 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 and display image in PHP and ajaxFolders and Files

Below is a screenshot of the folder structure and files I am using:

Uploading Profile Photo of a member in php and ajax

I have created a folder named 'profile' under 'xampp/htdocs' as I am using XAMPP. If you are using WAMP, create 'profile' folder under 'www'.

  1. Folder 'cfg' - In this folder dbconnect.php is kept, this is to connect to the MySQL database.
  2. Folder 'css' - Our custom stylesheet is in this folder
  3. Folder 'js' - We have the custom JavaScripts file
  4. Folder 'uploads' - Uploaded photo will be stored in this folder, if no photo is added by the user, it uses avatar.png as a default one.
  5. index.php is the screen to update user details and add/change/delete photo.
  6. login.php and logout.php - I have used a login page to update the photo
  7. process_image.php is the PHP program called from Ajax. This PHP program does many works like upload, delete, display photo.

Below is the screenshot of the page:

update profile picture - PHP ajax

Step 1 - Create a table in MySQL database for user profile details

Let us create a table named 'profile' in MySQL database. This table will have user details, like name, email, photo etc. I have a database called 'demo'. So, this table will be created in demo database. If you have an existing database other than demo you can also use it. Just make sure same table does not exist already. Table structure is given below:

PHP MySQL Set Profile Picture using ajax

Table has 4 columns.

  1. id - It is the unique id of a user, primary key and auto incremented
  2. name - Name of the user
  3. email - Email of the user
  4. address - Address of the user
  5. photo - Image file name of the photo of the user
  6. password - User password
Create table script with data for this table is given below, you can use this code to create the table. You can also download it from the download section later in this topic.

profile.sql

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

Use below script to connect to the database. Note that we have this database connection php program in 'cfg' folder. This is written once and used in every program where database connection is needed. This will be easy for maintenance and also will enable reusability of the code.

dbconnect.php

I am using mysqli_connect() function which needs 4 parameters.

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

For detail database connection understanding please read topic How to Connect to MySQL database in PHP using mysqli_connect.

Step 3 - Develop a page to display photo in the profile (index.php)

Profile page will have name, email and address displayed on the left-hand side. Profile photo will be displayed on the right. See below:

Upload user profile image and save to data base in PHP

Note that in actual user profile there could be many other details of the user. For our simplicity we are using only name, email and address. Now at this moment we assume that user has registered but not added a profile photo. So, "Add Profile Photo" button is displayed.

Check if user logged in and get user details

We initialized $upload_path as 'uploads/'. You can see it verifies if user is logged in by checking $_SESSION['email']. If it is not set, it redirects user to login.php. But if user is logged in, it selects details of the user from profile table.

Display user details

For updating user details a form will be used. But for updating photo we will use Ajax script.

Form to update user details

Display, change, delete photo

Let us see how photo is displayed and updated. There is a space for image preview. Let see the code:

If photo is available, it is displayed with option to change and delete photo. Two JavaScript functions, showUpload() and deleteImage() are called here to change and delete photo. <div class="select-photo">, is added for changing the photo. While changing the photo, this section will be visible using showUpload() function, initially it will be hidden.

Modal to display photo

A modal is defined to display the photo in the modal. Note that we are not displaying anything in the modal now, it will be displayed using JavaScript. See below code from index.php

PHP code after the form is submitted

It just takes the values from the form and updates the "profile" table in the database.

Here is the complete code for index.php

index.php

Step 4 - Write JavaScript/jQuery to preview, upload and delete a photo (upload.js)

Let us now see the JavaScript functions in upload.js file.

Preview Image - Function previewImage()

This function is called as soon as user selects photo. This function displays the preview of the photo selected by the user. Let's see the code for this function:

If the image file is correct, image is displayed within div defined for preview and source of image is used from URL.createObjectURL() method. This method creates an string containing a URL of the image object.

Function to upload photo

Upload button is used to upload the photo in the server. This function takes input photo and executes an Ajax script to run a php program (process_image.php) with the input file as parameter, this php program uploads the photo. Let's see the Ajax code:

A FormData() instance is created and the input image file with email are added in form_data. Then executing an Ajax script with the form_data as one of the parameters. Let's see all the parameters in Ajax call below:

  1. url: process_image.php - Call to php program which uploads the photo.
  2. dataType: text - Response of Ajax call is text only
  3. cache: false - We do not want browser to cache
  4. contentType: false - Since we are sending form_data with image file as input, we must set contentType as false to use enctype = multipart/form-data
  5. processData: false - This is also for form data, we do not want jQuery to process data before sending it to the server.
  6. data: form_data - input form data sent to the request
  7. type:post - Type must be post here for enctype = multipart/form-data
  8. success: When Ajax is successful, message about upload will be displayed.

    If the image is uploaded successfully, we want to display the image. In this case we just need to print the output of process_image.php, which will be displaying the image along with change and delete buttons.

process_image.php uploads the photo in the server and then updates profile table with the image file name.

If validations are successful, it first removes existing file, if any, from the server using unlink() function. Then image file is uploaded using move_uploaded_file().

Function deleteImage()

This function is called when user clicks on delete (x - button) button next to the photo. The function is called with two parameters - image file name and email. Function executes Ajax scripts to run process_image.php which deletes the image from database as well as from the server folder. Below is the code written in upload.js for this function.

Now, let's see the code for delete image section of process_image.php.

If delete flag is set, it updates database table with photo set as blank. Corresponding image file is removed using unlink() function. Since photo is removed now, we need to show the section to add the photo.

Function showUpload()

This function is called when user clicks on change photo button. This function simply displays the contents of <div> with class as "select-photo". See below code for this function:

You can see it simply changes the display property of the <div> to block, which means it will be visible now.

A modal is used to display the photo using JavaScript, name of the photo is a parameter to the modal. See below

"data-id" parameter is used to send the name of image file to the modal. See below JavaScript to display photo in a modal:

Below is the complete code of upload.js and process_image.php. There is a download section later in this topic, if you download the zip file, you will get all the scripts for this topic.

upload.js

process_image.php

Additionally, below code is for login.php and logout.php. Which are necessary for this application. To login, use email id = john@test.com, password = 123.

login.php

In logout.php, we are unsetting all variables and deleting the session. Then redirecting the user to the login page.

logout.php

Step 5 - Add CSS (style.css)

We need to add some styles. Very simple and basic styles are used here. You can always add better styles. See below:

style.css

Test the Application

Make sure in your XAMPP control panel Apache and MySQL services are running. Open the browser and run localhost/user. You will see login page, please enter email as "john@test.com" and password as "123" to login. You will see the profile page as displayed below:

Update user profile with photo in php and ajax

Try to update profile with or without photo.

Test all error cases also, like select invalid file type, select photo with size more than 2M. See if you get the proper error messages.

Our development and testing are completed now. Hope you could understand all the steps and you could test it successfully.

display user profile picture after login 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

  2. Note that here I have shown it for one user id. When users registered themselves in any application, they can upload photo while registering or can upload it later. I have assumed the user is already registered and he/she wants to update personal details and add/update/delete profile photo. So, this will be applicable to any user who has already registered.

download source code to update profile with photo in php with ajaxDownload Source Code

I have put all codes in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can directly use the code or you can modify them as per your requirements.

update profile with picture in php with ajaxConclusion

If you want to implement update profile for user with a photo, then I hope this topic will be helpful for you. I will say, not just for user profile, it can be used for other areas also, like a product where you want to update product details along with the photo of the product. If you find it useful, you can use it in your project or in any other web application with similar requirement.