To escape or not to escape

I see it too often in the forum and the docs: people using the esc() helper in a wrong way, or not using it when they actually should. For example, with input sanitization:

<?php $var = esc(get('var')) ?>

or using the ‘legacy’ html() version:

<h1><?php echo $page->title()->html() ?></h1>

:pensive:

Please use the toolkit Escape class and the corresponding esc() helper for what they are intended for: XSS (Cross Site Scripting) prevention.

<h1><?php echo $page->title()->esc() ?></h1>

or the more readible version:

<h1><?php echo $page->title()->escape() ?></h1>

or maybe for escaping URL parameters:

<a href="http://yoursite.com?some_untrusted_parameter=<?php echo esc($var, 'url') ?>">Go</a>

etc.

The Escape class was written to the help you prevent the first couple of issues described here: Cross Site Scripting Prevention - OWASP Cheat Sheet Series

Read the full documentation in the class to find out what every method is intended for.

2 Likes