Search

Laravel Security Helper Function: e for HTML Entities

November 16, 2016 —John Koster

The e function is a simple wrapper of PHP's htmlentities function. The e function utilizes the UTF-8 character encoding. The e function will sanitize user input when displaying it to the browser.

The signature for the e helper function is:

e($value)

Let's assume that a malicious user was posting on a forum and set the subject of their post to this:

1<script>alert("hello everyone");</script>

If the forum software did not sanitize user output, perfectly valid JavaScript code would be sent to the browser. Since browsers are overly happy to execute any JavaScript included in the document, any forum visitor would see an alert box with hello everyone every time a page was loaded that displayed that particular forum post.

To prevent this, use the e function to sanitize user input when sending it to the browser:

1$unsafeClientCode = '<script>alert("hello everyone");</script>';
2 
3$safeClientCode = e($unsafeClientCode);

The value of $safeClientCode would then be:

1&lt;script&gt;alert(&quot;hello everyone&quot;);&lt;/script&gt;gt;

At this point the browser will render a string that literally represents what they had typed.