How to update profile picture on a webpage using HTML, CSS, JAVASCRIPT & PHP

Here’s an example of how you can update a profile picture on a webpage using HTML, CSS, JavaScript, and PHP:

HTML:

				
					<div id="profile-picture">
  <img decoding="async" id="current-picture" src="current-picture.jpg" alt="Current Profile Picture">
  <form id="form">
    <input type="file" id="file-input">
    <input type="submit" value="Upload">
  </form>
</div>

				
			

CSS:

				
					#profile-picture {
  text-align: center;
}

#current- picture {
  width: 200px;
  height: 200px;
  border-radius: 100px;
}

#form {
  margin-top: 20px;
}

input[type="file"] {
  display: none;
}

				
			

JavaScript:

				
					const fileInput = document.getElementById("file-input");
const currentPicture = document.getElementById("current-picture");

fileInput.addEventListener("change", (event) => {
  const file = event.target.files[0];
  const reader = new FileReader();

  reader.onloadend = function () {
    currentPicture.src = reader.result;
  };

  reader.readAsDataURL(file);
});

document.getElementById("form").addEventListener("submit", (event) => {
  event.preventDefault();

  const formData = new FormData();
  formData.append("picture", fileInput.files[0]);

  fetch("upload.php", {
    method: "POST",
    body: formData,
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
    })
    .catch((error) => {
      console.error(error);
    });
});

				
			

PHP:

				
					<?php

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $file = $_FILES["picture"];

  $fileName = $file["name"];
  $fileTmpName = $file["tmp_name"];
  $fileSize = $file["size"];
  $fileError = $file["error"];
  $fileType = $file["type"];

  $fileExt = explode(".", $fileName);
  $fileActualExt = strtolower(end($fileExt));

  $allowed = array("jpg", "jpeg", "png");

  if (in_array($fileActualExt, $allowed)) {
    if ($fileError === 0) {
      if ($fileSize < 1000000) {
        $fileNameNew = "profile- picture." . $fileActualExt;
        $fileDestination = "uploads/" . $fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
        echo json_encode(array("message" => "Success"));
      } else {
        echo json_encode(array("message" => "File is too big"));
      }
    } else {
      echo json_encode(array("message" => "There was an error uploading your file"));
}
} else {
echo json_encode(array("message" => "Invalid file type"));
}
}

?>

				
			


This code creates a form that allows users to select an image file and submit it to the server for uploading. The JavaScript code listens for a change in the file input and updates the src attribute of the current profile picture `img` element. It also listens for a submit event on the form and makes a POST request to the server using fetch to upload the image. The PHP code on the server processes the uploaded image and returns a JSON response indicating whether the upload was successful or not.