This tutorial is very useful for those who just started developing in php field and it’s a very common script. You can find lots of similar scripts in world wide web, but I am posting for you and I hope this code become helpful to your project.
Here we are going to see how to upload multiple image using ajax and PHP.
Step 1: Folder Structure
css -- style.css js -- jquery.min.js uploads ajax.php index.php loader.gif
Step 2:
Include bellow jQuery library and stylesheet in your index.php file.
<link rel="stylesheet" type="text/css" href="css/style.css"> <script type="text/javascript" src="js/jquery.min.js"></script>
Step 3:
Add below ajax + html code to your index.php file.
<script type="text/javascript"> $(window).load(function(){ $("form[name='uploadfrm']").submit(function(event){ event.preventDefault(); $("#loading").show(); var formData = new FormData($(this)[0]); console.log(formData); $.ajax({ url: "ajax.php", type: "POST", data: formData, async: false, success: function(msg){ $("#loading").hide(); $('#uploadfrm')[0].reset(); // Reset form data }, cache: false, contentType: false, processData: false }); }); }); </script> <form name="uploadfrm" id="uploadfrm" method="post" enctype="multipart/form-data" action="ajax.php"> <div> <label>Upload your images:</label> </div> <div id="loading" class="none"> <img src="loader.gif" alt="Loading...."/> </div> <div> <input type="file" name="images[]" id="photoimg" multiple="true" accept="image/*" /> </div> <div> <input type="submit" name="upload" id="upload" value="Submit your images" /> </div> </form>
Step 4:
Create ajax.php file for upload files.
<?php $timestamp = time(); // Current timestamp $location = "uploads/"; // Location to store image $allow = array("jpg", "jpeg", "png"); // Allow certain filetypes on upload $images = $_FILES["images"]["name"]; // Get only image names from array $tmp_name = $_FILES["images"]["tmp_name"]; for($i=0; $i<count($images); $i++){ $ext = strtolower(pathinfo($images[$i], PATHINFO_EXTENSION)); if(in_array($ext, $allow)){ $image = strtolower($images[$i]); // Create image name with lower case move_uploaded_file($tmp_name[$i], $location.$timestamp.$image); // The file has been moved correctly }else{ echo "Error This file ". $images[$i] ." is not allowed."; echo "<br />"; } } ?>
That's It, Thanks You.
You Can Also Read 30 Best PHP Interview Questions