What are the best practices for handling file uploads in PHP to ensure a smooth and error-free process for users?

File uploads in PHP can be prone to errors such as file size limitations, file type restrictions, and potential security vulnerabilities. To ensure a smooth and error-free process for users, it is important to implement proper validation, error handling, and security measures when handling file uploads in PHP.

<?php
// Check if the file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
    // Specify the allowed file types
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    $file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

    // Validate file type
    if(!in_array($file_extension, $allowed_types)){
        echo "Invalid file type. Please upload a JPG, JPEG, PNG, or GIF file.";
    } else {
        // Move the uploaded file to the desired directory
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
        echo "File uploaded successfully.";
    }
} else {
    echo "Error uploading file. Please try again.";
}
?>