Reputation: 21
I looked over multiple posts but couldn't find the solution.
I want to add htmlspecialchars over $_SERVER variables on the following code to prevent from XSS.
echo '<script type="text/javascript">window.location = "'.htmlspecialchars($_SERVER['HTTP_HOST']).htmlspecialchars($_SERVER['REQUEST_URI']).'";</script>';
The problem is that the function breaks the URL by escaping quotes and ampersand
On similar topics, some users suggested using urlencode instead of htmlspecialchars, but urlencode is not meant to prevent xss on the HTML code above.
Upvotes: 1
Views: 251
Reputation: 33237
Your example puts the value in JavaScript, not in HTML. The thing with XSS protection is that there is no one-size-fits-all. You need to adjust your approach based on the context you output to.
For JavaScript it is JSON. You need to encode your value as JSON and output it to JavaScript. Because JSON is a subset of JavaScript, you can just output it as-is without quotes or further escaping.
echo '<script type="text/javascript">window.location = '.
json_encode($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']).
';</script>';
Upvotes: 2