How can PHP developers prevent file upload attacks and ensure the integrity of uploaded images?

To prevent file upload attacks and ensure the integrity of uploaded images, PHP developers can validate file types, restrict file sizes, and use image processing libraries to check image content. Additionally, storing uploaded files in a secure directory outside of the web root can help prevent direct access to uploaded files.

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

// Restrict file size
$maxFileSize = 2 * 1024 * 1024; // 2MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die('File size is too large. Maximum file size allowed is 2MB.');
}

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

if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
    echo 'File is valid, and was successfully uploaded.';
} else {
    echo 'File upload failed.';
}