What are best practices for handling images in PHP code?

When handling images in PHP code, it is important to validate and sanitize user input to prevent security vulnerabilities such as file upload attacks. It is also recommended to use image manipulation libraries like GD or Imagick for resizing, cropping, and other image processing tasks. Additionally, consider storing images outside of the web root directory to prevent direct access.

// Example of validating and processing an uploaded image file

// Validate file type
$allowedTypes = ['image/jpeg', 'image/png'];
if (!in_array($_FILES['image']['type'], $allowedTypes)) {
    die('Invalid file type. Only JPEG and PNG files are allowed.');
}

// Sanitize file name
$fileName = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['image']['name']);

// Move uploaded file to desired directory
$uploadPath = 'uploads/';
if (!move_uploaded_file($_FILES['image']['tmp_name'], $uploadPath . $fileName)) {
    die('Failed to upload file.');
}

// Process uploaded image using GD library
$image = imagecreatefromjpeg($uploadPath . $fileName);
$newWidth = 200;
$newHeight = 150;
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($image), imagesy($image));

// Save resized image
imagejpeg($resizedImage, $uploadPath . 'resized_' . $fileName);

// Clean up
imagedestroy($image);
imagedestroy($resizedImage);