What are the potential pitfalls of not properly encoding and decoding special characters in PHP?

Not properly encoding and decoding special characters in PHP can lead to security vulnerabilities such as cross-site scripting (XSS) attacks, where an attacker can inject malicious code into a web page. To prevent this, it is important to use functions like htmlspecialchars() when outputting user input to HTML and urldecode() when decoding URL-encoded strings.

// Encoding special characters before outputting to HTML
$user_input = "<script>alert('XSS attack');</script>";
$encoded_input = htmlspecialchars($user_input, ENT_QUOTES);

echo $encoded_input;

// Decoding URL-encoded strings
$url_encoded = "Hello%20World%21";
$decoded_string = urldecode($url_encoded);

echo $decoded_string;