What best practices should be followed when handling file uploads in PHP forms?

When handling file uploads in PHP forms, it is important to ensure that the uploaded files are secure and that the server can handle them properly. Some best practices to follow include validating file types, checking file size limits, and storing uploaded files in a secure directory outside of the web root.

<?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 = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    if(!in_array($file_type, $allowed_types)){
        echo "Invalid file type. Only JPG, JPEG, PNG, GIF files are allowed.";
        exit;
    }
    
    // Validate file size
    if($file_size > 2097152){ // 2MB
        echo "File is too large. Maximum file size is 2MB.";
        exit;
    }
    
    // Store uploaded file in a secure directory
    $upload_dir = 'uploads/';
    if(!is_dir($upload_dir)){
        mkdir($upload_dir);
    }
    $new_file_name = $upload_dir . $file_name;
    if(move_uploaded_file($file_tmp, $new_file_name)){
        echo "File uploaded successfully.";
    } else {
        echo "Error uploading file.";
    }
} else {
    echo "Error uploading file.";
}
?>