What are the best practices for handling file uploads in PHP to ensure smooth functionality?

When handling file uploads in PHP, it is important to ensure that the file size is within acceptable limits, validate the file type to prevent malicious uploads, and store the file securely on the server. To achieve smooth functionality, use PHP's built-in file upload functionality and sanitize user input to prevent any security vulnerabilities.

<?php
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
    $file_name = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_tmp = $_FILES['file']['tmp_name'];
    $file_type = $_FILES['file']['type'];
    
    // Specify allowed file types
    $allowed_types = array('image/jpeg', 'image/png', 'image/gif');
    
    // Check if file type is allowed
    if(in_array($file_type, $allowed_types)){
        // Move the uploaded file to a secure location
        move_uploaded_file($file_tmp, "uploads/" . $file_name);
        echo "File uploaded successfully!";
    } else {
        echo "Invalid file type. Allowed types: jpeg, png, gif";
    }
} else {
    echo "Error uploading file. Please try again.";
}
?>