What are the best practices for managing image uploads and permissions in PHP?

When managing image uploads and permissions in PHP, it is important to validate the uploaded file to ensure it is an actual image file and not a malicious script. Additionally, setting proper permissions on the uploaded image files can help prevent unauthorized access or execution.

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

// Set proper permissions on uploaded image file
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
    chmod($uploadFile, 0644);
    echo 'File uploaded successfully.';
} else {
    echo 'File upload failed.';
}