Mark Biwojno
Mark Biwojno

Reputation: 75

Security risk from using $_SERVER['REQUEST_URI'] in forms

I'm using echo $_SERVER['REQUEST_URI']; to output parts of a HTML form to a user.

I'm worried about the potential for Cross Site Scripting attack, where a link to offsite JavaScript file could be injected into the page. However, I cannot filter "=" in my output, because it is a relevant part of my query string. Might filtering equals signs output be enough to prevent a CSS attack? Or is the simply a bad practice (using user generated GET query strings in a form)?

Here's the potential vulnerability:

//Attacker types this into the browser:
vulnerabilesite.com/=query=?querystringhere/?<script type="text/javascript">       
maliciouswebsite.com/js.js</script>
//People viewing the website using that link will now execute the following code:
<script type="text/javascript"> /link-to-malicious-javascript </script>

Upvotes: 1

Views: 2112

Answers (1)

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60577

Use the following htmlspecialchars call to escape $_SERVER['REQUEST_URI'] safely for content and attributes, even if you are using single quotes for your HTML attributes. If using an encoding other than UTF-8, make sure to substitute the correct encoding.

echo htmlspecialchars( $_SERVER['REQUEST_URI'], ENT_QUOTES, 'UTF-8' );

This is the same code as is used by html_escape function in the CodeIgniter framework.

Alternatively:

echo htmlspecialchars( $_SERVER['REQUEST_URI'], ENT_QUOTES | ENT_HTML5, 'UTF-8' );

Upvotes: 2

Related Questions