What are the best practices for validating and restricting file types (e.g., gif, jpg, png) when uploading images using PHP?

When uploading images using PHP, it is essential to validate and restrict file types to prevent malicious files from being uploaded to the server. One way to do this is by checking the file extension and MIME type of the uploaded file against a list of allowed file types. This can help ensure that only safe image formats like gif, jpg, and png are accepted.

// Define an array of allowed file types
$allowedTypes = ['image/gif', 'image/jpeg', 'image/png'];

// Get the file extension and MIME type of the uploaded file
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$mime = mime_content_type($_FILES['file']['tmp_name']);

// Check if the file type is allowed
if (in_array($mime, $allowedTypes) && ($extension == 'gif' || $extension == 'jpg' || $extension == 'png')) {
    // File type is allowed, proceed with uploading the file
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    echo 'File uploaded successfully!';
} else {
    // File type is not allowed
    echo 'Invalid file type. Only gif, jpg, and png files are allowed.';
}