How can XSS vulnerabilities be exploited in PHP scripts, and what measures can be taken to prevent them?

XSS vulnerabilities in PHP scripts can be exploited by injecting malicious scripts into input fields or URLs, which can then be executed in a user's browser. To prevent this, developers should sanitize user input, encode output data, and use functions like htmlspecialchars() to escape special characters.

// Sanitize user input
$user_input = htmlspecialchars($_POST['user_input']);

// Output sanitized data
echo $user_input;