5

$address and $cityState is user provided, stored in a DB, and available for others to view as shown below. Is there risk of XSS? Should htmlspecialchars() also be used on it?

<img src="http://maps.google.com/maps/api/staticmap?markers=color:blue|<?php echo(urlencode($address.' '.$cityState));?>&amp;zoom=14&amp;size=400x400&amp;sensor=false" alt="Map" />
huysentruitw
  • 27,376
  • 9
  • 90
  • 133
user1032531
  • 24,767
  • 68
  • 217
  • 387

3 Answers3

8

Yes, htmlspecialchars should also be used - you're first encoding the URL to be URL-safe, and then you're building it into an HTML-attribute, which 'requires' the HTML-style escaping.

After using both encodings it's no longer possible to inject arbitrary code on your end of the scale, so if any risks remain they're on Google's end. As such you can then consider this code safe.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
  • Thanks Niels. So, do `urlencode()` first? For instance `htmlspecialchars(urlencode($badString))` – user1032531 May 02 '13 at 12:46
  • Yes, first encode the URL so it is safe on its own (and especially the space is correctly encoded), then encode it so it's fit for embedding into HTML. – Niels Keurentjes May 02 '13 at 12:48
3

There is no magic wand PHP function what will protect you from all. Every protection is 100% safe till day it hacked. You just need to understand from where and how your site can be hacked and improve your protection every day.

You can get some interesting tips from article about XSS prevention.

Also from php.net urlencode documentation:

<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>
Narek
  • 3,813
  • 4
  • 42
  • 58
0

urlencode() should not be used for protection from XSS. htmlspecialchars() is the way to go, but you are never safe.

Vlad
  • 795
  • 1
  • 12
  • 35