Lesson 32 โข Advanced
Image Uploads & Processing ๐ผ๏ธ
Handle user image uploads securely, resize and crop with GD and Imagick, and optimize for the web with WebP conversion.
What You'll Learn in This Lesson
- โข Securely validate and handle file uploads
- โข Prevent malicious file upload attacks
- โข Resize, crop, and create thumbnails with GD
- โข Convert images to WebP for 30-50% smaller files
- โข Generate responsive image sizes automatically
Secure File Uploads
File uploads are one of the most dangerous features in web apps. Never trust the file extension โ attackers rename shell.php to shell.php.jpg. Always validate the actual MIME type using finfo, enforce size limits, and generate random filenames to prevent path traversal attacks.
Try It: Secure Upload Validation
Validate file type, size, and extension; generate safe filenames
// Secure Image Upload Handling in PHP
console.log("=== File Upload Security Checklist ===");
console.log();
class ImageUploader {
constructor(config) {
this.maxSize = config.maxSize || 5 * 1024 * 1024; // 5MB
this.allowedTypes = config.allowedTypes || ["image/jpeg", "image/png", "image/webp", "image/gif"];
this.uploadDir = config.uploadDir || "/uploads/images/";
this.errors = [];
}
validate(file) {
this.errors = [];
// Check file exists
if (!file || !fil
...Resizing & Optimization
Serving a 4000ร3000 original to mobile users wastes bandwidth. Generate multiple sizes (thumbnail, small, medium, large) and convert to WebP format for 30-50% smaller files with the same visual quality. GD is built into PHP; Imagick offers higher quality for professional use.
Try It: Image Resizing Pipeline
Generate responsive image sizes and convert to WebP
// Image Resizing & Optimization with GD and Imagick
console.log("=== PHP Image Libraries: GD vs Imagick ===");
console.log();
console.log(" Feature | GD Library | Imagick");
console.log(" โโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโ");
console.log(" Built-in | Yes (usually) | Requires extension");
console.log(" Format support | JPEG, PNG, GIF | 200+ formats");
console.log(" Quality | Good | Excellent");
console.log(" Memory usage
...โ ๏ธ Common Mistakes
finfo_file() to check actual MIME type from file bytes.../ to escape your upload directory. Always generate random names.๐ Quick Reference โ Image Processing
| Function | Purpose |
|---|---|
| imagecreatefromjpeg() | Load JPEG into GD resource |
| imagecopyresampled() | Resize with high-quality resampling |
| imagewebp() | Save image as WebP format |
| finfo_file() | Detect real MIME type from file bytes |
| getimagesize() | Get image dimensions and type |
๐ Lesson Complete!
You can now handle image uploads securely and optimize images for the web! Next, learn to generate PDFs and export files.
Sign up for free to track which lessons you've completed and get learning reminders.