Image upload is a common requirement in website development. To ensure both the security and user experience of image uploads, PHP provides convenient tools for implementing this functionality. This article will guide you through how to handle image uploads and processing in PHP forms step by step.
First, we need to create a form in HTML that allows users to select and upload an image. Here is a basic image upload form code:
<!DOCTYPE html> <html> <head> <title>Image Upload</title> </head> <body> <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" value="Upload"> </form> </body> </html>
Once the user selects an image and submits the form, we need to handle the image upload with PHP. Before uploading, we must validate the image type and size and store it in a specified directory.
<?php $targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["image"]["name"]); $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); // Check image type $allowedTypes = array('jpg', 'jpeg', 'png', 'gif'); if (!in_array($imageFileType, $allowedTypes)) { echo "Only JPG, JPEG, PNG, or GIF images are allowed"; exit; } // Check image size $maxSize = 5 * 1024 * 1024; // 5MB if ($_FILES["image"]["size"] > $maxSize) { echo "Image size cannot exceed 5MB"; exit; } // Move image to target directory if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) { echo "Image uploaded successfully"; } else { echo "Image upload failed"; } ?>
Once the image is successfully uploaded, we can perform various processing operations, such as resizing, cropping, or adding watermarks. The following example demonstrates how to resize an image to 200x200 pixels:
<?php $targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["image"]["name"]); // Resize image $thumbWidth = 200; $thumbHeight = 200; $sourceImage = imagecreatefromjpeg($targetFile); $sourceWidth = imagesx($sourceImage); $sourceHeight = imagesy($sourceImage); $thumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight); imagecopyresized($thumbImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $sourceWidth, $sourceHeight); $thumbFile = $targetDir . "thumb_" . basename($_FILES["image"]["name"]); imagejpeg($thumbImage, $thumbFile); imagedestroy($sourceImage); imagedestroy($thumbImage); echo "Image processing successful"; ?>
The above code resizes the image to a 200x200 thumbnail and saves it in the same directory on the server.
Through the steps outlined above, we can easily implement image upload and processing in PHP forms. Depending on your needs, you can add additional features such as watermarking, cropping, or more advanced image editing operations. These techniques will help developers handle image uploads more efficiently.