What best practices should be followed when handling file uploads in PHP to prevent errors and improve security?

When handling file uploads in PHP, it is important to validate the file type, size, and content to prevent errors and improve security. Additionally, it is recommended to store the uploaded files outside of the web root directory to prevent direct access. Implementing proper error handling and sanitizing user input can also help mitigate potential security risks.

<?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'];
    
    // Validate file type
    $file_type = pathinfo($file_name, PATHINFO_EXTENSION);
    if($file_type != "jpg" && $file_type != "png" && $file_type != "jpeg" && $file_type != "gif"){
        echo "Only JPG, JPEG, PNG, GIF files are allowed.";
        exit;
    }

    // Validate file size
    if($file_size > 500000){
        echo "File size must be less than 500 KB";
        exit;
    }

    // Move uploaded file to desired directory
    move_uploaded_file($file_tmp, "uploads/" . $file_name);
    echo "File uploaded successfully.";
} else {
    echo "Error uploading file.";
}
?>