views:

74

answers:

5

when I have a value like this in the database ("foo")

how can I echo it without any conflict with html code

notice

<input type="text" value="<? echo '"foo"'; ?>" />

the result will be like this

<input type="text" value=""foo"" />

how can I fix it ?

A: 
<?php

echo "<input type='text' value='{$foo}' />" ;

?>
Chris J
Just using ' instead of " would bring the same problem if the database would contain a '.
ZeissS
this will just move from " to ', and it still allows for XSS.
knittl
+2  A: 

You can use htmlentities to overcome this problem like so:

<input type="text" value="<? echo htmlentities('"foo"'); ?>" />

this will return

<input type="text" value="&quot;foo&quot;" />

avoiding any conflict with html.

GeekTantra
this function generate unprintable characters when I used it with other languages beside English .
Waseem Abu Senjer
Yes, you need to pass in the charset when it's UTF-8 (or anything other than ISO-8859-1): `htmlentities($var, ENT_QUOTES, 'utf-8')`. However it is generally easier just to use `htmlspecialchars` instead; there is no need to entity-encode the other characters.
bobince
+2  A: 

use urlencode or htmlspecialchars

<a href="<?php echo urlencode($dburl)?>" title="<?php echo htmlspecialchars($dbvalue)?>">link</a>
knittl
+1  A: 

htmlspecialchars() basically, for example

<input type="text" value="<? echo htmlspecialchars($value, ENT_QUOTES); ?>" />

The ENT_QUOTES is optional and also encodes the single quote ' .

I used $value since I'm not sure what exactly you have in the database (with or without quotes?) but it will sit in some kind of variable if you want to use it anyway, so, I called that $value.

Since the above is a bit unwieldy I made a wrapper for it:

// htmlents($string)
function htmlents($string) {
  return htmlspecialchars($string, ENT_QUOTES);
}

So you can

<input type="text" value="<? echo htmlents($value); ?>" />

Not to be confused with the existing htmlentities(), which encodes all non-standard characters. htmlspecialchars() only encodes &, <, >, " and ', which is more appropriate for UTF8 pages (all your webpages are UTF8, right? ;-).

MSpreij
yes my pages are UTF8
Waseem Abu Senjer
I shorten the shortcut even further, by defining `function h($s) { echo htmlspecialchars($s, ENT_QUOTES); }`. Then you can write just `<?php h($value); ?>`.
bobince
A: 
symcbean
fails to HTML-escape, causing XSS vulnerabilities. And personally I consider the `print` version much *less* readable. You lose proper consistent HTML and PHP indentation when you do it like that.
bobince