In this tutorial, we will see you how to upload multiple images using PHP. In many cases, we need to upload multiple images and submit to the server for the different scenario. Then we need to keep the uploaded documents and file with our server for future reference or share with others.
In HTML, we need to add the form with enctype=”multipart/form-data” attribute for handle the file input process and file input tag with multiple attribute and define tag name as array format.
In PHP, move_uploaded_file() method use to save the chosen file into the server. It has tow parameter, one is temp file path of our chosen image and another one is the destination path to save the image to the server.
HTML Form wtih PHP Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<html> <head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <style> .m-50{ margin-top:100px;} .upfile-info { border: solid 1px #cfcfcf; padding: 10px 5px; border-radius: 5px; background: #c4d6ff; } </style> </head> <body> <div class="row m-50"> <div class="col-md-offset-2 col-md-6"> <form method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="email">Choose any image file:</label> <input type="file" class="form-control" id="upload_image" name="upload_image[]" multiple required accept="image/*" /> </div> <div class="form-group"> <button type="submit" class="btn btn-success" id="sumbit" name="sumbit" >Upload Images</button> </div> </form> </div> </div> <div class="row"> <div class="col-md-offset-2 col-md-6"> <?php if(isset($_POST['sumbit'])){ foreach($_FILES['upload_image']['name'] as $key=>$val){ $uploadfile = $_FILES["upload_image"]["tmp_name"][$key]; $file_name = uniqid().$_FILES['upload_image']['name'][$key]; $target_file_path = "uploads/".$file_name; if(move_uploaded_file($_FILES["upload_image"]["tmp_name"][$key], $target_file_path)){ echo "<p class='upfile-info'>$file_name - Uploaded</p>"; } } } ?> </div> </div> </body> </html> |