How can you ensure the security of image uploads in PHP to prevent vulnerabilities?

To ensure the security of image uploads in PHP and prevent vulnerabilities, you should validate the file type, restrict the file size, and store the uploaded files in a secure directory outside of the web root.

// Validate file type
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
$extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);

if (!in_array($extension, $allowedExtensions)) {
    die('Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.');
}

// Restrict file size
$maxFileSize = 2 * 1024 * 1024; // 2 MB
if ($_FILES['image']['size'] > $maxFileSize) {
    die('File size exceeds the limit of 2 MB.');
}

// Store uploaded file in a secure directory
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['image']['name']);

if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Failed to upload file.';
}