How can PHP developers ensure that their code is secure when handling image uploads and display on a website?

To ensure that PHP code is secure when handling image uploads and display on a website, developers should validate file types, sanitize file names, store files outside the web root directory, and use image manipulation libraries to resize and compress images.

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

// Sanitize file name
$filename = strtolower(preg_replace("/[^a-zA-Z0-9.]/", "", $_FILES['image']['name']));

// Store file outside web root directory
$upload_path = '/var/www/uploads/';
move_uploaded_file($_FILES['image']['tmp_name'], $upload_path . $filename);

// Use image manipulation library to resize and compress image
$image = imagecreatefromjpeg($upload_path . $filename);
$new_image = imagescale($image, 200);
imagejpeg($new_image, $upload_path . 'resized_' . $filename);
imagedestroy($image);
imagedestroy($new_image);