What are the potential pitfalls of directly outputting variables in PHP and how can they be avoided?

Directly outputting variables in PHP can lead to security vulnerabilities such as cross-site scripting (XSS) attacks if the variables contain user input. To avoid this, always sanitize and validate user input before outputting it to the browser. One way to do this is by using htmlspecialchars() function to escape special characters.

// Example of avoiding direct output of variables
$userInput = "<script>alert('XSS attack');</script>";
$cleanInput = htmlspecialchars($userInput);
echo $cleanInput;