What are the best practices for handling file uploads in PHP forms to ensure data integrity and security?

When handling file uploads in PHP forms, it is crucial to validate and sanitize the uploaded file to ensure data integrity and security. This includes checking file size, file type, and renaming the file to prevent malicious code execution. Additionally, storing the uploaded files in a secure directory outside of the web root can help prevent unauthorized access.

<?php
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    // Validate file size and type
    if($_FILES['file']['size'] <= 5000000 && in_array(pathinfo($uploadFile, PATHINFO_EXTENSION), array('jpg', 'jpeg', 'png', 'gif'))){
        // Move uploaded file to secure directory
        if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)){
            echo 'File uploaded successfully.';
        } else {
            echo 'Failed to upload file.';
        }
    } else {
        echo 'Invalid file. Please upload a file less than 5MB in size and of type JPG, JPEG, PNG, or GIF.';
    }
}
?>