What are best practices for handling file uploads in PHP to ensure security and efficiency?

When handling file uploads in PHP, it is important to ensure security by validating file types, checking file sizes, and storing files in a secure location. Efficiency can be improved by setting appropriate upload limits and handling file uploads asynchronously.

<?php
// Check if the file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK) {
    // Validate file type
    $allowed_types = array('image/jpeg', 'image/png', 'image/gif');
    if(in_array($_FILES['file']['type'], $allowed_types)) {
        // Check file size
        if($_FILES['file']['size'] < 5000000) {
            // Move the uploaded file to a secure location
            move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
            echo 'File uploaded successfully!';
        } else {
            echo 'File is too large.';
        }
    } else {
        echo 'Invalid file type.';
    }
} else {
    echo 'Error uploading file.';
}
?>