Introduction
Uploading multiple images is a common requirement in web development, allowing users to share and manage visual content on websites. In this guide, we’ll walk through the process of creating a PHP script to handle the upload of multiple images.
1. Create HTML Form for File Upload
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Multiple Image Upload</title> </head> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="images[]" multiple accept="image/*"> <button type="submit" name="submit">Upload Images</button> </form> </body> </html>
This HTML form includes an input field with the multiple
attribute, allowing users to select and upload multiple images. The form’s enctype
attribute is set to “multipart/form-data” to support file uploads.
2. Create PHP Script to Handle Upload
<?php if (isset($_POST['submit'])) { $uploadDir = 'uploads/'; $uploadedImages = array(); foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) { $file_name = $_FILES['images']['name'][$key]; $file_tmp = $_FILES['images']['tmp_name'][$key]; $targetPath = $uploadDir . $file_name; if (move_uploaded_file($file_tmp, $targetPath)) { $uploadedImages[] = $file_name; } } if (!empty($uploadedImages)) { echo "Images uploaded successfully: " . implode(', ', $uploadedImages); } else { echo "No images uploaded."; } } ?>
This PHP script checks if the form is submitted, iterates through each uploaded image, and moves it to the specified upload directory. It then echoes a success message with the names of the uploaded images.
3. Ensure Proper Permissions
Make sure the ‘uploads’ directory has the necessary permissions to allow file uploads. You can set the permissions using the following command in a terminal:
chmod -R 755 uploads/
4. Display Uploaded Images
To display the uploaded images, you can create another PHP script or modify the existing one to generate HTML code to showcase the images. Here’s a simple example:
<?php $uploadDir = 'uploads/'; $uploadedImages = scandir($uploadDir); foreach ($uploadedImages as $image) { if (!in_array($image, ['.', '..'])) { echo '<img src="' . $uploadDir . $image . '" alt="Uploaded Image">'; } } ?>
This script uses scandir
to retrieve the list of uploaded images and displays them using HTML <img>
tags.
With these steps, you’ve created a basic system for uploading and displaying multiple images using PHP. Keep in mind that additional features such as image validation, size restrictions, and database integration can be added based on your specific requirements.