What are some best practices for user management and file uploading in PHP?

Issue: When managing users and allowing file uploads in PHP, it is important to implement proper security measures to prevent unauthorized access and potential security vulnerabilities. Code snippet:

// User management
// Ensure user authentication before allowing access to sensitive information or actions
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// File uploading
// Validate file type and size before allowing upload
$allowed_types = array('image/jpeg', 'image/png', 'image/gif');
$max_size = 5 * 1024 * 1024; // 5MB

if (in_array($_FILES['file']['type'], $allowed_types) && $_FILES['file']['size'] <= $max_size) {
    // Process file upload
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
} else {
    echo 'Invalid file type or size.';
}