What are the best practices for handling file uploads in PHP to ensure successful file transfer?

When handling file uploads in PHP, it is important to ensure that the server is properly configured to accept file uploads, validate the file type and size to prevent malicious uploads, and handle errors gracefully to provide feedback to the user.

<?php
// Check if the file was uploaded without errors
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
    // Validate file type
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($_FILES['file']['type'], $allowed_types)) {
        echo 'Invalid file type. Please upload a JPEG, PNG, or GIF file.';
    } else {
        // Validate file size
        if ($_FILES['file']['size'] > 5242880) { // 5MB limit
            echo 'File is too large. Please upload a file smaller than 5MB.';
        } else {
            // Move the uploaded file to a permanent location
            move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
            echo 'File uploaded successfully.';
        }
    }
} else {
    echo 'An error occurred during file upload. Please try again.';
}
?>