What are some best practices for structuring PHP code to handle dynamic content based on user input?

When handling dynamic content based on user input in PHP, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One best practice is to use conditional statements to dynamically generate content based on user input. Additionally, separating the logic from the presentation by using a template engine like Twig can make the code more maintainable and easier to read.

<?php
// Sanitize and validate user input
$user_input = isset($_POST['user_input']) ? htmlspecialchars($_POST['user_input']) : '';

// Conditional statement to generate dynamic content
if ($user_input === 'option1') {
    echo 'Content for option 1';
} elseif ($user_input === 'option2') {
    echo 'Content for option 2';
} else {
    echo 'Default content';
}
?>