views:

29

answers:

2

Might be a naive question, but I am wondering if I have data that will be sent to the browser - specifically in the value of an input (type="text") (and I can guarantee the value will be double-quoted), is it safe to consider the data sanitized if I merely replace " with \"

I guess it's easier to see code (sorry, PHP). Is this safe given untrusted data?

$name = str_replace('"', '\\"', $name);
echo '<input type="text" name="name" value="' . $name .'" />';

Could multibyte data ruin the party? Does that depend on the page's charset? Anything I'm overlooking?

TIA!

A: 

I think that would do it.

htmlspecialchars is the general solution for preventing XSS attacks, and it seems to only convert <, >, ", &, and, depending on parameters, ', and does nothing else. Sounds like there isn't any significant character encoding black magic to worry about for such a simple task.

Matchu
A: 

Comment in reponse to Matchu (because I see no "add comment" button at all):

Right, normal ASCII input would be fully protected by only escaping the double quote in this example.

However, what about multibyte values in $name? str_replace does not allow you to specify the charset of the variable (htmlspecialchars does), so is it thus vulnerable to the kind of attack explained nicely below?

http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string

Even though that problem discusses data going to the database, I'm thinking it might also apply to data going to the browser as well?