What are the potential security risks associated with directly echoing user input in PHP?

Directly echoing user input in PHP can lead to security risks such as cross-site scripting (XSS) attacks, where malicious scripts can be injected and executed in the context of a user's browser. To prevent this, it is essential to properly sanitize and validate user input before echoing it back to the browser. One way to do this is by using the htmlspecialchars function to convert special characters into HTML entities, which will prevent the execution of any malicious scripts.

// Sanitize and echo user input using htmlspecialchars
$userInput = $_POST['user_input'];
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');