As a bonus, if you're interested, I like it when the behavior of a templating library is to escape by default. It makes it much harder to make a mistake and leave an XSS flaw somewhere. Here's a quick and simple way that could be done.
PHP Code:
class Escaper
{
private $value;
public function __construct($value)
{
$this->value = $value;
}
public function __toString()
{
return htmlspecialchars($this->value, ENT_QUOTES);
}
public function getRaw()
{
return $this->value;
}
}
Escaper wraps some string value, and when an Escaper object is used in a string context, it returns the value escaped.
PHP Code:
$taintedContent = '<b>Hello</b>, <i>World</i>';
$safeContent = new Escaper($taintedContent);
// Now we can use it in a string, and escaping happens automatically
echo '<p>' . $safeContent . '</p>';
// If we're sure we want the unescaped value, we can still get that
echo '<p>' . $safeContent->getRaw() . '</p>';
Bookmarks