What are the best practices for handling file uploads in PHP, including security considerations?

When handling file uploads in PHP, it is important to validate file types, limit file sizes, and store uploaded files in a secure location outside the web root directory to prevent direct access. Additionally, consider using a unique filename to prevent overwriting existing files and sanitize user input to prevent injection attacks.

<?php
// Check if the file was uploaded without errors
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (in_array($_FILES['file']['type'], $allowedTypes)) {
        // Limit file size
        if ($_FILES['file']['size'] <= 5000000) {
            // Move uploaded file to a secure location
            $uploadDir = 'uploads/';
            $uploadFile = $uploadDir . basename($_FILES['file']['name']);
            move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);
            echo 'File uploaded successfully!';
        } else {
            echo 'File size exceeds limit!';
        }
    } else {
        echo 'Invalid file type!';
    }
} else {
    echo 'Error uploading file!';
}
?>