How can PHP be used to prevent XSS attacks when malicious JavaScript code is appended to a URL parameter?

To prevent XSS attacks when malicious JavaScript code is appended to a URL parameter, you can use PHP's htmlspecialchars function to encode any user input before displaying it on the webpage. This function will convert special characters like <, >, " and & into their HTML entities, preventing the browser from interpreting them as code.

$url_param = $_GET[&#039;param&#039;]; // Retrieve the URL parameter
$encoded_param = htmlspecialchars($url_param, ENT_QUOTES, &#039;UTF-8&#039;); // Encode the parameter to prevent XSS attacks
echo $encoded_param; // Display the encoded parameter on the webpage