To upload an image using JavaScript and handle the upload on the server side with a PHP script, you can follow these steps:
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Upload</title> </head> <body> <h2>Upload Image</h2> <form id="imageUploadForm" enctype="multipart/form-data"> <input type="file" id="imageFile" name="imageFile" accept="image/*" required> <button type="submit">Upload</button> </form> <div id="uploadStatus"></div> <script> document.getElementById("imageUploadForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent the default form submission // Create a FormData object to hold the file const formData = new FormData(); const fileInput = document.getElementById("imageFile").files[0]; formData.append("imageFile", fileInput); // Send the image via an AJAX request const xhr = new XMLHttpRequest(); xhr.open("POST", "upload.php", true); // Set up the callback to update status xhr.onload = function () { const response = document.getElementById("uploadStatus"); if (xhr.status === 200) { response.innerHTML = "Image uploaded successfully!"; } else { response.innerHTML = "Error uploading image."; } }; // Send the request xhr.send(formData); }); </script> </body> </html>
upload.php
php<?php // Directory to store uploaded images $targetDir = "pic/"; $targetFile = $targetDir . basename($_FILES["imageFile"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); // Check if image file is a valid image or not if (isset($_POST["submit"])) { $check = getimagesize($_FILES["imageFile"]["tmp_name"]); if ($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($targetFile)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Limit file size (5MB in this case) if ($_FILES["imageFile"]["size"] > 5000000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats $allowedTypes = ['jpg', 'png', 'jpeg', 'gif']; if (!in_array($imageFileType, $allowedTypes)) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 due to an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // Try to upload file } else { if (move_uploaded_file($_FILES["imageFile"]["tmp_name"], $targetFile)) { echo "The file " . htmlspecialchars(basename($_FILES["imageFile"]["name"])) . " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?>
pic
folder in the root directory where the upload.php
script will store uploaded images.chmod 755
or chmod 777
depending on your server's configuration).upload.php
), which will then save the image in the pic
folder.This solution uses XMLHttpRequest
to send the image asynchronously without reloading the page. The PHP script checks file type, size, and whether the image is already present before uploading.